Get File Size and File Name of Local Files with JavaScript

Using the HTML5 File API, we can get information about files on our users’ computers — before they try to upload them. This is great news for error checking file type and file size. Here’s a demo:


As you can see, we grabbed the following info from the File interface:

  • size: The file size, in bytes.
  • lastModified: The last time the file was changed, as a Unix timestamp.
  • name: The filename (but not the path).
  • extension: The file’s extension. (This one isn’t included in File, but we get it with the file_extension function, included further down this page.)

Here’s the jQuery code that makes that happen:

$(function() {
	if (window.File) {
		$('#upload').bind('change', function() {
			var fileinfo = 'size: ' + this.files[0].size + '<br>' +
			'lastModified: ' + this.files[0].lastModified + '<br>' + 
			'name: ' + this.files[0].name + '<br>' +
			'extension: ' + file_extension(this.files[0].name);
			$('#fileinfo').html(fileinfo);
		});
	} else {
		$('#fileinfo').html('Your browser does not support the File API.');
	}
});

(You could do that in straight JavaScript too, it would just take some extra characters.)

The if (window.File) bit is a check to see if the user’s browser supports the File API. Good news is that over 90% of the current browser market share supports it.

A file extension check is one of the most commonly needed error checks, so we put together a quick JavaScript function that grabs the file extension from any filename. It’ll return null if the file has no extension. Here it is:

function file_extension(filename) {
	if (filename.lastIndexOf('.') > -1) {
		return filename.substr((filename.lastIndexOf('.')+1));
	} else {
		return null;
	}
}

Finally, here’s the HTML that we used in the example above:

<input type="file" id="upload"><br>
<span id="fileinfo"></span>

There’s not much to it; we do all the heavy lifting in the JavaScript.


Comments

Loading…

This post was published on February 7th, 2017 by Robert James Reese in the following categories: JavaScript and jQuery. Before using any of the code or other content in this post, you must read and agree to our terms of use.