Home > Web Front-end > JS Tutorial > body text

Javascript combined with fileReader to upload pictures_javascript skills

WBOY
Release: 2016-05-16 16:16:50
Original
1350 people have browsed it

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?

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template