Javascript uses fileReader to upload images and javascript to upload files

Source: Internet
Author: User

Javascript uses fileReader to upload images and javascript to upload files

I will not explain the File API in detail here. We will use the File handle to read the File content. This is achieved through FileReader and through the FileReader interface, we can asynchronously load the file content into the memory and assign a js variable.

Copy codeThe 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.tar get. 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 (afile [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 javascript and fileReader to upload images. Do you like it?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.