Upload image after preview

The specific thing to do is to have a button on the page. After the user selects the image to be uploaded, the page will preview the image to be uploaded.
The previous practice is to upload the image to be uploaded to the server through Ajax, and add an image to the page after the server responds successfully. If the upload is wrong, you need to delete the image on the server as well.
This can now be done via H5 with the following code:

document.querySelector('#upfile').onchange = function (evt) {
    var files = evt.target.files;
    for(var i = 0, f; f = files[i]; i++){
        if(!f.type.match('image.*')) continue;
        
        var reader = new FileReader();
        reader.onload = (function(theFile){
            return function(e){
                var img = document.createElement('img');
                img.title = theFile.name;
                img.src = e.target.result;
                document.body.appendChild(img); //Where do you want to insert here  
            }
        })(f);
        reader.readAsDataURL(f);
    }  
}

If you want to upload multiple images at a time, the code is as follows:

document.querySelector('#upfile').onchange = function () {
     var fileReader = new FileReader();
      fileReader.onload = function (e) {
          if (fileReader.readyState == FileReader.DONE) {
              var img = document.createElement('img');
              img.src = this.result;
              document.body.appendChild(img); //The example simply inserts the body
          }
      }
     // load multiple files at once
     var i = 0, src = this.files;
     fileReader.readAsDataURL(src[i]);
     fileReader.onloadend = function () {
         i++;
         if (i < src.length) fileReader.readAsDataURL(src[i]);
     }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326676611&siteId=291194637