Home Web Front-end JS Tutorial How to make image upload preview component in H5

How to make image upload preview component in H5

Mar 10, 2018 pm 04:19 PM
html5 components Preview

This time I will show you how to make an image upload preview component in H5. What are the precautions for making an image upload preview component in H5? The following is a practical case, let’s take a look.

My development environment is Windows 10 and the test browsers are Chrome and Firefox
If you encounter incompatible browsers, you can try to upgrade the browser or Google it (~ ̄▽ ̄)~

1 .Single selection and multiple selection of files

By default, belongs to single selection. Adding the multiple attribute allows multiple selection of files

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <label>单选:<input type="file"/></label>
        <label>多选:<input type="file" multiple="multiple"/></label>
    </body></html>
Copy after login

2 .Get the file object

Open the browser console and select the file to see the console changes

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body> 
        <label>可以这样:<input type="file" multiple="multiple" onchange="getFilesInfo(this.files)"/></label>
        <script>
            function getFilesInfo(f){                console.log(f);
            }        </script>
        <label>也可以这样:<input id="files" type="file" multiple="multiple" /></label>
        <script>
            function getFilesInfo2(evt) {                var files = evt.target.files; 
                console.log(files);
            }            document.getElementById(&#39;files&#39;).addEventListener(&#39;change&#39;, getFilesInfo2, false);        </script>
        <label>还可以这样:<input id="fileInput" type="file" multiple="multiple" onchange="getFilesInfo3()"/></label>
        <script>
            function getFilesInfo3(){                var files=document.getElementById("fileInput").files;                console.log(files);
            }        </script>
    </body></html>
Copy after login

3. Common attributes

In the second step, we have already looked in the console When we get to the file, let’s expand it and see what common attributes there are.

Common attribute description:
name-file name
size-size
type-file type
lastModified-last Modification date

Come on, let’s try to output some information to the page

<!doctype html><html>
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <input type="file" id="files"  multiple />
        <output id="list"></output>
        <script>
            function handleFileSelect(evt) {                var files = evt.target.files; //如果你是单选那就直接evt.target.files[0]
                var output = []; 
                for(var i = 0, f; f = files[i]; i++) {
                    output.push(&#39;<li><strong>&#39;, f.name, &#39;</strong> (&#39;, f.type || &#39;n/a&#39;, &#39;) - &#39;,
                        f.size, &#39; bytes, last modified: &#39;,
                        f.lastModifiedDate.toLocaleDateString(), &#39;</li>&#39;);
                }                document.getElementById(&#39;list&#39;).innerHTML = &#39;<ul>&#39; + output.join(&#39;&#39;) + &#39;</ul>&#39;;
            } 
            document.getElementById(&#39;files&#39;).addEventListener(&#39;change&#39;, handleFileSelect, false);        </script>
    </body> </html>
Copy after login

4. Limit file size and file format

When it comes to uploading previews of images, it is not allowed The size and format of uploaded files will not be filtered.
Assume that we only allow jpg and png to be uploaded and the file size is within 2mb. It is very simple and only the file information can be judged.
If you don’t know the file you want to filter Type You can check the file type in the console and then copy and paste
Of course you can also set accept="image/*" in the input tag to only allow the input of image files

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h3>过滤出图片</h3>
        <input type="file" id="files"   multiple accept="image/*"  />
        <output id="list"></output> 
        <script>
            function handleFileSelect(evt) {                var files = evt.target.files;                var output = [];                for(var i = 0, f; f = files[i]; i++) {                    if(f.size<1024*1024*2&&(f.type=="image/png"||f.type=="image/jpeg")){//<===这里
                        output.push(&#39;<li><strong>&#39;, f.name, &#39;</strong> (&#39;, f.type || &#39;n/a&#39;, &#39;) - &#39;,
                        f.size, &#39; bytes, last modified: &#39;,
                        f.lastModifiedDate.toLocaleDateString(), &#39;</li>&#39;);
                    }
                }                document.getElementById(&#39;list&#39;).innerHTML = &#39;<ul>&#39; + output.join(&#39;&#39;) + &#39;</ul>&#39;;
            } 
            document.getElementById(&#39;files&#39;).addEventListener(&#39;change&#39;, handleFileSelect, false);        </script>
    </body> </html>
Copy after login

5. Preview example

Preview is implemented by dynamically creating img tags and binding ObjectURL to the src attribute of img tags
Example

<!DOCTYPE html><html>
   <head>
       <meta charset="UTF-8">
       <title></title>
   </head>
   <body>
       <h3>预览</h3>
       <input type="file" id="files"  multiple accept="image/*" />
       <output id="list"></output>  
       <script>
           function handleFileSelect(evt) {               var files = evt.target.files;               var output = [];               for(var i = 0, f; f = files[i]; i++) {                   if(f.size<1024*1024*2&&(f.type=="image/png"||f.type=="image/jpeg")){
                       output.push("![]("+URL.createObjectURL(f)+")"); 
                   }
               }               document.getElementById(&#39;list&#39;).innerHTML = &#39;<ul>&#39; + output.join(&#39;&#39;) + &#39;</ul>&#39;;
           }           document.getElementById(&#39;files&#39;).addEventListener(&#39;change&#39;, handleFileSelect, false);       </script>
   </body></html>
Copy after login

6. Single image upload preview example

Example

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h3>简单预览示例</h3>
        <label id="fileBox" style="border: 1px #ccc solid;display:block;width: 100px;height:100px;background-clip:border-box;background-origin:padding-box;background-size:cover">
            <input type="file"  hidden="hidden" style="display: none;" onchange="fileSelect(this.files)"/>
         </label>
        <script>
            function fileSelect(f) { 
                if(!f){                    return;
                }  
                f=f[0];                if(f.size<1024*1024*2&&(f.type=="image/png"||f.type=="image/jpeg")){                    document.getElementById(&#39;fileBox&#39;).style.backgroundImage="url(" + URL.createObjectURL(f)+ ")";
                } 
                
            }         </script>
    </body> </html>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to use s-xlsx to import and export Excel files

How to use JavaScript to save text data

File upload extension made with jQuery


The above is the detailed content of How to make image upload preview component in H5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

See all articles