Front End Picture Preview

Picture preview is a very significant function of front end development, especially if you want to contact with users directly and improve the user experience. And now we have two methods to achieve this effect. One is "FileReader" function, it's very easy to use and understand, the other is "window.URL", it has two functions —— "window.URL.createObjectURL()" and "window.URL.revokeObjectURL()", their parameters should be a file or blob object.

1. FileReader

It's easy, so let's see an example first:
var input = document.querySelector("input"); input.addEventListener("change", function(event){ var files = this.files; for (var i = 0; i < files.length; i++){ var file = files[i]; var fr = new FileReader(); fr.onload = function(e){ var tempimg = new Image(); tempimg.src = e.target.result; document.body.appendChild(tempimg); } fr.readAsDataURL(file); } }, false);
The "FileReader" object has lots of functions, if we want to read pictures, we should use "readAsDataURL()", if we want to read text files, we should use "readAsText()". Actually, it also has three events, "progress", "load" and "error". We can get the file by using "fr.result" in "load" event, and we can also get the progress of file loading by using "event.loaded/event.total" attributes in "progress" event. For more details, just click this link.

2. window.URL

Actually, the "window.URL" function belongs to browsers, so it will be more fast and efficient than "FileReader". And we don't need to wait the object loaded, therefore the number of code lines will less than "FileReader". Let's see the example:
var input = document.querySelector("input"); input.addEventListener("change", function(event){ var files = this.files; for (var i = 0; i < files.length; i++){ var file = files[i]; var urlobj = window[window.webkitURL ? 'webkitURL' : 'URL']['createObjectURL'](file); var tempimg = new Image(); tempimg.src = urlobj; document.body.appendChild(tempimg); } }, false);
For compatibility, we should write like this : "window[window.webkitURL ? 'webkitURL' : 'URL']['createObjectURL']". We should remember the "URL" is an attribute of window. So we can use "[ ]" function to get the attribute. In order to optimize memory, we would better use "window.URL.revokeObjectURL()" function to revoke the URL object. Obviously, our browsers will revoke it automatically, but it's better to cancel by ourself. Little tips: If you want to select more than one files at the same time, just add "multiple='multiple'" attribute to input button. The following is a small demo, you can select one picture and see it preview.
(That's all)