Home  >  Article  >  Web Front-end  >  Javascript combined with fileReader to upload pictures_javascript skills

Javascript combined with fileReader to upload pictures_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:16:501308browse

The File API will not be explained in detail here. Friends, you can do it yourself. Now we will use the file handle to read the file content. This is achieved through FileReader. Through the FileReader interface, we can asynchronously Load the file content into memory and assign it to a js variable.

Copy code The code is as follows:

function getImgSrc(target, callback) {
If (window.FileReader) {
      var oPreviewImg = null, oFReader = new window.FileReader();
oFReader.onload = function (oFREvent) {
oPreviewImg = new Image();
              var type = target.files[0].type.split("/")[1];
          var src = oFREvent.target.result;
oPreviewImg.src = src;
If (typeof callback == "function") {
                   callback(oPreviewImg, target, type, src);
            }
               return oPreviewImg.src;
        };
          return (function () {
            var aFiles = target.files;
                  if (aFiles.length === 0) {
                  return;
            }
If (!IsImgType(aFiles[0].type)) {
alert("You must select a valid image file!");
                  return;
            }
If (aFiles[0].size > 1024 * 1024) {
                   target.value = "";
alert('Please upload image file size less than 1M.');
                  return;
            }
            oFReader.readAsDataURL(aFiles[0]);
         })();
}
If (navigator.appName === "Microsoft Internet Explorer") {
          return (function () {
document.getElementById("imagePreview").filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = target.value;
         })();
}
}

The above is the key code for uploading images using javascript combined with fileReader. Do you guys like it?

Statement:
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