How can you determine the file size in JavaScript?

梦想与她 提交于 2019-11-27 04:52:53

Short answer, you cannot

Also, Check on jGuru How can you check the file size from JavaScript in a form with an input type of file?

You will find some important points

Well the answer is very simple, you cannot.

Reason: The browser security does not allow the scripts (Javascript/VBScript) or even applets and ActiveX Controls to read files from the local hard disk. You can only read files if your code is signed by some Certificate Authority (CA). Now the input type "FILE" also does not have the permission to read files. We cannot do anything about that since thats what HTML says. So since it cannot read files, it cannot find the size of the file with which the input tag is associated. Since it cannot find the file size, there is no function exposed by JavaScript/VBScript to return the file size. But if you need to find the file size, say in order to restrict the size of the file uploaded to your web-server. Then you can do so by counting the file contents on the server-side, once the user submits it to the server. Thats what many of the free e-mail providers like www.hotmail.com do.

Keith Adler

As you know IE supports the fileSize property of an image. No such luck in other browsers ... however, you should be able to modify this script:

http://natbat.net/2008/Aug/27/addSizes/

It uses JSON to read HTTP headers of files and display their actual file size. That should help you prevent people uploading large animated GIFs.

As for getting the dimensions:

var img = new Image();
theImage.src = "someimage.jpg";
actualwidth = theImage.width;
actualheight = theImage.height;

This of course is a pure client-side approach to something best handled server-side.

Actually, with HTML5, this is now possible,
read more information here.

Server side validation is always a better bet, but in your case, I can see why you would want to do this client side.

Also, it seems that others may have misread the question, and that the images that Daniel want to test are already uploaded, in which case there is a fairly simple method of doing so (provided the images are on the same domain as the script).

var getFileSize = function(address, responseHandler) {
  var req = new XMLHttpRequest();  

  req.open('head', address, true);  
  req.onreadystatechange = responseHandler;
  req.send(null);  
}

var responseHandler = function(resp) {
  if ( this.readyState == 1 ) {
    this.abort();
  }
  console.log(this.getResponseHeader("Content-length"));
};

getFileSize("http://stackoverflow.com/content/img/so/logo.png", responseHandler);

Boom. This example works in FF3 and probably 2. Since you're using Greasemonkey to do this, browser compatibility doesn't seem like an issue.

I'm not certain if Greasemonkey shares the same XML RPC domain restrictions, but if the images files that you need are on a different domain than the script, then you might need to look into using some iframe magic.

Client side validation is insufficient to accomplish your goal. A simple post request will allow the user to upload any image they want no matter what html or javascript you serve them.

You could set a maximum file size in your HTML where they upload files.

<input type="hidden" name="MAX_FILE_SIZE" value="10000000">

(max_file_size in bytes).

However, this is an "undocumented/unsupported" item of some browsers. You are best to actually check the filesize on the server once it's been uploaded.

You could also use a Flash or Java applet to handle the upload and check the filesize there. See http://www.masrizal.com/product/custom%20tag/cf_flashmultiupload/docs%20&%20examples/example.cfm and http://www.saschawenning.de/labor/flash8/fileUpload/ for examples.

The DOM attribute img.fileSize will return the actual file size of the referenced <img>. Access to the img object can be obtained using JQuery or the DOM 'images' collection. However, this is an IE only extension.

Another approach is to omit the height and width attributes in the <img> tag, so that the full image is downloaded, then use img.height and img.width to determine the size of the downloaded image. This code could be put into the user's profile editor page as an intermediate step between having someone enter their signature as HTML, then showing them a preview of their signature. Clunky, I have to admit, but possible.

If you are worried about huge images, set a max upload size as Richy C. mentioned, but also resize the uploaded image on the server and use the resized version.

Facebook does this for most of the uploaded images so that reasonably size images are served. Even converting them to png format in some (most?) cases, which drive the creative group nuts because of "lost quality".

What you should be able to do is an AJAX HEAD request of the image url, which just gets the header of the file rather than the contents, so is much faster. One of the headers you will get back is Content-Length, and that will tell you the size of the image in bytes.

More details here.

You can do that file HTML5 JS File API

You can test run the below codes in my web IDE (but please use google chrome or FF): http://codesocialist.com/#/?s=bN

The below codes retrieve the filetype and filesize for you :)

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {

    // Great success! All the File APIs are supported.
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes </strong></li>');
        }

        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }

    // Bind Event Listener
    document.getElementById('files').addEventListener('change', handleFileSelect, false);

} else {
    alert('The File APIs are not fully supported in this browser.');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!