Site icon Sir Codex

How to Open Dropped Files Using HTML5

Why Open Local Files in JavaScript?

Uploading files from an HTML form is clunky. People often use it when transferring multi-megabyte photographs from their camera to a web server. Assuming they locate the file, the upload could take several minutes only to find it was the wrong photo, an unsupported format, or a larger file size than permitted. Until now, developers had to rely on Flash or other plugins to provide a better user experience.

Pre-processing in JavaScript offers a number of benefits:

The FileReader object

FileReader forms part of the W3C File API and offers four methods to asynchronously load data from a file referenced in a File object:

In the following code we’ll use the first two methods to load and display text and image files.

Opening Files Asynchronously in JavaScript

Here’s our original ParseFile() function which is passed a File object when it is selected or dropped onto the #filedrag element:


// output file information
function ParseFile(file) {

	Output(
		"<p>File information: <strong>" + file.name +
		"</strong> type: <strong>" + file.type +
		"</strong> size: <strong>" + file.size +
		"</strong> bytes</p>"
	);
	
}

Following the status update, we’ll check if we have a text file (text/plain, text/html, text/css, etc.), load it using the FileReader.readAsText() method and display the result (after escaping < and > characters):


	// display text
	if (file.type.indexOf("text") == 0) {
		var reader = new FileReader();
		reader.onload = function(e) {
			Output(
				"<p><strong>" + file.name + ":</strong></p><pre>" + 
				e.target.result.replace(/</g, "&lt;").replace(/>/g, "&gt;") +
				"</pre>"
			);
		}
		reader.readAsText(file);
	}

Similarly, we can check whether we have an image file (image/jpeg, image/gif, image/png etc.), load it into a data URL using the FileReader.readAsDataURL() method, and pass the result to the src attribute of an img tag:


	// display an image
	if (file.type.indexOf("image") == 0) {
		var reader = new FileReader();
		reader.onload = function(e) {
			Output(
				"<p><strong>" + file.name + ":</strong><br />" +
				'<img src="' + e.target.result + '" /></p>'
			);
		}
		reader.readAsDataURL(file);
	}

Source Link: http://www.sitepoint.com/html5-javascript-open-dropped-files/

Exit mobile version