Upload image quick preview HTML5 FileReader + Window.URL method

In web pages, it is often necessary to upload pictures and preview them. In most cases, images are uploaded to the back-end through ajax, and then the upload status and results are fed back to the front-end for preview. Here we introduce two quick upload image preview methods, which can quickly preview the image without the back-end participation.
FileReader document
Window.URL document

1. Get File object

Both preview methods need to get the file object of the < input type ='File '> control first

var fileinput = Document.getElementById('id');
var File = fileinput.files[0];  //Get the first File object
//When there are multiple uploaded files, multiple File objects can be obtained by cycling
var fileList = this.files;
        for( var i = 0 ; i < fileList.length ; i++ ){


File.name  //Returns the name of the File referenced by the current File object, read-only 
File.size  //Returns the size of the file, read-only, in bytes
File.type  //Return the file type, for example, PNG image is "image/png", read-only
File.lastModifiedDate //Returns the last modified date of the current file. If the last modified date of the file cannot be obtained, the current date is used instead. Read only

//You can set the upload file type and the maximum upload file size according to the above properties


Construction object

if (window.FileReader){    //Check whether the browser supports
    var reader = new FileReader();  //Construct FileReader object
    //If not, only other image preview methods are used


reader.readAsArrayBuffer(File);  //Read file as ArrayBuffer object format
reader.readAsBinaryString(File); //Read file as binary data
reader.readAsDataURL(File);   //Read the file and return its URL, suitable for picture preview
reader.readAsText(File,encoding='UTF-8') //Read the file as text, and specify the encoding method
reader.abort()  //Terminate read operation


reader.onloadstart = function(){
    //Triggered when the file starts reading

reader.onprogress = function(event){
    //Triggered regularly during file reading
    //Read file size: event.loaded
    //Total file size: event.total
    //The above two parameters can be used with the < progress > tag of HTML to make a read progress bar

reader.onabort = function(){
    //Triggered when file read aborted

reader.onerror = function(){
    //Triggered when an error occurs in a read operation

reader.onload = function(){
    //Triggered when the read operation completes successfully

reader.onloadend = function(){
    //When the read operation is completed, the call is successful or failed. The handler is called after onload or onerror.


reader.error  //Error reading file. Read only

reader.readyState  //Indicates the current state of the FileReader object. There are three states: 0: no data has been loaded; 1: data is being loaded; 2: all read requests have been completed

reader.result   //The read file content. This property is only valid after the read operation is completed, and the data format depends on which method the read operation is initiated by. Read only

Preview method

Using the readAsDataURL() method, after reading, the URL of the image is saved in the result attribute, and assigned to the src attribute of < img >


Get URL object

var URL = window.URL || window.webkitURL;

Create picture URL

var imageURL = URL.createObjectURL(File);
//After creation, you can directly use theURL´╝îAssign to<img>Of src attribute

Release URL


4. Examples

$("input[type=file]").change(function(){   //Upload image preview
    var fileobj = $(this)[0];
    if (fileobj && fileobj.files[0]){
        var headimage = fileobj.files[0]
        if (headimage.type.split('/')[0] == 'image'){
            if(headimage.size/1024/1024 <= 2 ){
                    if (typeof FileReader != 'undefined'){
                        var reader = new FileReader();
                        reader.onload = function(){
                            var dataURL = reader.result;
                        var URL = window.URL || window.webkitURL;
                        var imageURL = URL.createObjectURL(headimage);
                alert("Picture size must be less than 2 M")
                fileobj.value = '';
                $('#pic_name').text("Upload picture failed");
            alert("Upload file must be in picture format");
            fileobj.value = '';
            $('#pic_name').text("Upload picture failed");

Tags: Attribute encoding less

Posted on Sat, 02 May 2020 15:44:42 -0700 by ciaran