Front end picture preview

Most of the time, we need to upload pictures. If we first upload the pictures to the server and then display the returned results on the front end, the cost of such operation performance is too large. If there are too many pictures, we will almost cry, and in case of an upload error to delete, it is unimaginable. Therefore, we need to first display the pictures on the front end, and then confirm that there is no problem by the user, and then upload them uniformly. This is ideal.

input

type=file

As we all know, to upload pictures on the front end, we cannot do without an input element of < input > type = file, which allows users to select one or more files.

    <input type="file">

At this point, click the input element to browse the local file and select upload. However, at this time, we can only select one file, not multiple. In this case, you need another attribute multiple of the < input > tag

multiple

The multipla attribute allows users to select multiple files. It is an attribute that does not need a value. In other words, as long as this attribute appears on your input tag, it will support multi file selection regardless of its value. Generally speaking, when we use multiple, we will only use its attribute name without adding value to it

    <input type='file' multiple>

accept

If you try the above tags and attributes, you will find that your can select not only image files, but also various other files. But generally speaking, what we need is only image files. As for other things, whatever you like, as long as you don't come out to hinder me. So at this time, we need the attribute of accept to restrict. The accept property accepts comma separated MIME type strings:

1. accept='image/png' perhaps accept='.png' --admit of only interpretation .png Format picture
2. accept='iamge/png,image/jpeg' perhaps accept='.png, .jpg .jpeg' accept .png .jpeg .jpg Format picture
3. accept='image/*' Accept all types of image 


    <input type='file' multiple accetp='image/*'>

Note: 'image / *' in some browsers (Webkit browsers such as Chrome and Safari) the response is relatively slow, which can be replaced by the following methods

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

style

Generally speaking, we will set input to display:none, and then set its display style through label

    // css

    input{
        display:none;
    }
    label{
        // About label styles
    }

    // html

    <input type='file' multiple accept='image/png, image/jpeg, image/jpg, image/svg, image/gif' id='inputFile'>
    <label for="inputFile">Upload pictures</label>

FileList object

The selected file passes through htmlinputelement The files attribute returns a FileList object, which is a list containing many file files. Each file object contains the following information:

1. name: file name
2. lastModified: Last modification time of the file (in the form of timestamp)
3. lastModifiedDate: Last modification time of file( UNIX timestamp (form)
4. size:  File size( byte (unit)
5. type: file MIME type

We can listen to the change event through the input tag:

    //  js

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

    function changeHandler(e) {
        var files = e.target.files;
        console.log(files) // Here we can get the information of the selected file. It should be noted that files is a class array object.
    } 

FileReader or object URL

When we get the file object information files, how do we preview it on the page? Here are two methods: FileReader or object URL.
How should these two methods be used and what is the difference?

1. FileReader

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

  1. readerAsDataURL(file): read the file and save it in the result attribute as a data URI

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

  3. Error event: an error event is triggered after the file fails to load

  4. Progress event: the progress event is triggered during the process of reading the file. This event can be approximately (triggered at intervals, not real-time response) to monitor the file upload progress. This method has three attributes: lengthComputable, loaded, and total.

usage:

    files.forEach(function(item) {
        var reader = new FileReader();
        reader.readAsDataURL(item);
        reader.onprogress = function(e) {
            if (e.lengthComputable) {
                // Simply print the progress information to the console
                console.log(e.loaded / e.total + '%') 
            }
        }
        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!')
        }
    })

2. Object URL

An object URL refers to a URL that references data stored in a File or Blob. When using the object URL, you don't have to read the data into JavaScript like FIleReader. It can reference the URL address in memory.

Method of creating object URL: 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
        }
    }

usage:

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

difference:

Zhao Kao

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

  2. FileReader.readAsDataURL returns a base64 format containing more bytes, and createObejctURL returns a URL with hash.

  3. Due to the different return forms, FileReader Readerasdataurl will take up more memory, but it will automatically release memory when you no longer use it, while createObjectURL can release memory only when your page is closed or you manually call revokeObejctURL.

  4. In terms of compatibility: createObjectURL and FileReader Readerasdataurl is compatible with IE10 + and all modern mainstream browsers

  5. createObjectURL is relative to FileReader Readerasdataurl, high efficiency. However, if there are many pictures, you'd better clear the memory manually. You can pass the URL as a parameter directly to the window URL. revokeObjectURL(). Compatible writing:

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

Simple implementation:

    // css

    input{
        display:none;
    }
    label{
        // About label styles
    }

    // html

    <input type='file' multiple accept='image/png, image/jpeg, image/jpg, image/svg, image/gif' id='inputFile'>
    <label for="inputFile">Upload pictures</label>

    // 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)
        }
    }



Tags: Front-end Web Development

Posted by ih8telepathy.cm on Mon, 02 May 2022 15:32:47 +0300