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?