Requirement analysis: When uploading images, if you do not limit the size of the uploaded images, the consequences will be very serious. So how can we solve a tough problem? There are two ways:
1) Background processing : That is, AJAX POST is submitted to the background, the image is uploaded to the server, and then the image size is obtained for processing.
2) Front-end processing : That is, using Javascript to obtain the image size.
Obviously the first way is very bad. Because the file needs to be uploaded to the server first, if the file is large, the Internet is not very fast, and you need to wait for a long time, which treats the symptoms but not the root cause.
Function analysis:
Here I will only introduce the different approaches of IE and FireFox.
IE6:
Keyword: fileSize onreadystatechange complete
In IE6, the file size can be obtained through the fileSize attribute of the Img object, but the correct value of this fileSize attribute is established in the complete of the onreadystatechange event, that is,
onreadystatechange="Javascript:sizeCheck(this);">
function sizeCheck(img) {
if(img.readyState == "complete") {
alert(img.fileSize ; Path, only the image name can be obtained. However, the browser provides an interface such as nsIDOMFile, so you need to obtain the processed path through getAsDataURL(), but this path does not affect the display of the image src.
nsIDOMFile interface:
DOMString getAsBinary();
DOMString getAsDataURL();
DOMString getAsText(in DOMString encoding);
Copy code
The code is as follows:
img.src = obj.files[0].getAsDataUrl() ;
alert(obj.files[0].fileSize);
}
The above are the processing methods of two different browsers, so how to integrate them? I will post a small example I made below, in which I use JQuery to facilitate the acquisition of objects.
Copy code
The code is as follows:
Check uploaded image size