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.
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?