Most of the time we will have the picture upload function requirements, if we upload the picture to the server first, and then return the results to display in the front end, such operation performance overhead is too large, if the picture is more than one, it is almost crying, and in case of the upload error to delete, it is unimaginable. Therefore, we need to display the pictures in the front end first, and then the users confirm that there is no problem, and then upload them uniformly, which is more ideal.

input

type=file

As we all know, the only way to upload images in the front end is to have an input element with type=file, which allows the user to select one or more files.

    <input type="file">Copy the code

At this point, we click on the Input element to browse the local file and select upload. However, at this point we can only select one file, not multiple. You need multiple, the other attribute of the tag

multiple

The multipla property allows the user to select multiple files. It is a valueless property, meaning that as long as it appears on your input tag, it supports multiple file selection regardless of its value. In general, when we use multiple, we just use the attribute name and don’t add value to it

    <input type='file' multiple>Copy the code

accept

If you try the above tags and attributes, you will find that you can select not only the image file, but also a variety of other files. But generally the only thing we need is the image file, and as for the rest, we can do whatever we want, as long as it doesn’t get in my way. So we need the accept attribute to limit this. The ACCEPT attribute accepts a comma-separated MIME type string:

1. accept='image/png'Or accept ='.png'PNG format only. Accept ='iamge/png,image/jpeg'Or accept ='.png, .jpg .jpeg'PNG. Jpeg. JPG format'image/*'Accept all types of image <inputtype='file' multiple accetp='image/*'>Copy the code

Note: ‘image/*’ is slow in some browsers (Webkit browsers such as Chrome and Safari) and can be replaced with the following method

    <<input type="file" multiple accept='image/png, image/jpeg, image/jpg, image/svg, image/gif'> Copy the code

style

Typically we set the input to display: None, and then style it with the label

// css input{ display:none; } label{// about label style} // HTML <inputtype='file' multiple accept='image/png, image/jpeg, image/jpg, image/svg, image/gif' id='inputFile'>
    <label for="inputFile"> Upload image </label>Copy the code

The FileList object

The selected file returns a FileList object using the HTMLInputElement. Files property. This object is a list of file files. Each file object contains the following information:

Name: file name 2. LastModified: time when the file was lastModified (timestamp format) 3. LastModifiedDate: time when the file was lastModified (UNIX timestamp format) 4. File size (byte) 5.type: MIME type of the fileCopy the code

We can listen for the change event on the input tag:

    //  js

    document.getElementById('inputFile').addEventListener('change', changeHandler, false);

    functionchangeHandler(e) { var files = e.target.files; Console. log(files) // Here we can get information about the selected file. Note that files is an array-like object. }Copy the code

FileReader or Object URL

After we get the file object information files, how to preview it on the page, there are two methods: FileReader or object URL. How do you use these two methods, and what’s the difference?

1. FileReader

FileReader implements an asynchronous reading mechanism. He must first create an instance of FileReader through the FileReader() constructor. This example implements the following methods and events (in parts) :

  1. ReaderAsDataURL (file): Reads a file and stores it as a data URI in the Result property

  2. Load event: The load event is triggered after the file is successfully loaded

  3. Error event: An error event is triggered when a file fails to be loaded

  4. Progress event: The progress event is triggered during the reading of a file. This event can listen for file upload progress approximately (at intervals, not in real time). This method has three attributes: lengthComputable (whether progress information is available), Loaded (how much has been loaded), and total.

usage:

    files.forEach(function(item) {
        var reader = new FileReader();
        reader.readAsDataURL(item);
        reader.onprogress = function(e) {
            if(e.logthcomputable) {// Simply print the progress information to the console console.log(E.loaded/e.total +)The '%') 
            }
        }
        reader.onload = function(e) {
            var image = new Image()
            image.src = e.target.result
            body.appendChild(image)
        }
        reader.onerror = function(e) {
            console.log('there is an error! ')}})Copy the code

2. The object URL

Object urls refer to urls that reference data stored in files or BLObs. Instead of reading the data into JavaScript like FIleReader, object urls can be used by referencing in-memory urls.

Create the object URL methods: window. URL. CreateObjectURL (). Compatible writing:

    function creatObjectURL(file) {
        if (window.URL) {
            return window.URL.createObjectURL(file);
        } else if (window.webkitURL) {
            return window.webkitURL.createObjectURL(file);
        } else {
            return null
        }
    }Copy the code

usage:

    files.forEach(function(item) {
        var url = createObjectURL(item)
        var image = new Image()
        image.src = url
        body.appendChild(image)
    })Copy the code

The difference between:

Ginseng (zhao) (chao)

  1. FileReader is an asynchronous operation, while the object URL is a synchronous operation

  2. Filereader. readAsDataURL returns a base64 format with more bytes, and createObejctURL returns a HASH URL.

  3. Because both return form is different, FileReader. ReaderAsDataURL takes up more memory, but when you no longer use of his time, he will automatically release the memory, CreateObjectURL will only release memory if your page is closed or if you manually call revokeObejctURL.

  4. From compatibility for: createObjectURL and FileReader readerAsDataURL are compatible with ie 10 + and modern all major browsers

  5. Relative FileReader createObjectURL readerAsDataURL, efficiency is higher. But if the picture is more, it is best to manually clear memory, can pass the URL as a parameter directly to the window. The URL. RevokeObjectURL (). Compatible writing:

     function revokeObjectURL(url) {
         if (widnow.URL) {
             return window.URL.revokeObjectURL(url)
         } else {
             return window.webkitURL.revokeObjectURL(url)
         }
     }Copy the code

Simple implementation:

// css input{ display:none; } label{// about label style} // HTML <inputtype='file' multiple accept='image/png, image/jpeg, image/jpg, image/svg, image/gif' id='inputFile'>
    <label for="inputFile"// js var inputFile = document.getelementById ('inputFile')
    var body = document.body || document.getElementsByTagName('body')[0]

    inputFile.addEventListener('change', changeHandler, false)

    function changeHandler(e) {
        var files = Array.from(e.target.files)
        files.forEach(function(item) {
            var image = new Image()
            image.src = createObjectURL(item)
            body.appendChild(image)
            image.onload = function() {
                revokeObjectURL(this.src)
            }
        })
    }

    function createObjectURL(file) {
        if (window.URL) {
            return window.URL.createObjectURL(file)
        } else {
            return window.webkitURL.createObjectURL(file)
        }
    }

    function revokeObjectURL(file) {
        if (window.URL) {
            return window.URL.revokeObjectURL(file)
        } else {
            return window.webkitURL.revokeObjectURL(file)
        }
    }Copy the code