Preview the image before uploading javascript and HTML5
I. The FileList object and the file object FileList object indicate the list of files selected by the user. In HTML4, only one file can be placed in the file control, but in html5. by adding the multiple attribute, the file control allows multiple files to be placed at a time. Each selected file in the control is a file object, and the FileList object is a list of file objects. For example, the following code: select the file <input type = "file" id = "file" multiple size = "80"/> <input type = "button" onclick = "ShowFileName (); "value =" File Upload "/> press ctrl to select multiple files. The JS Code is as follows:
function ShowFileName() { var files = document.getElementById("file").files; for(var i = 0; i < files.length; i+=1) { var file = files[i]; console.log(file); console.log(file.name); }}
First, let's print out the attributes of the file object. In safari, see the attributes of the file name, size, last modification time, and type; 2. Add a Blob Object in HTML5 to represent the original binary data. The file object mentioned above also inherits the Blob Object. The Blob object has two attributes, the size attribute indicates the byte length of a Blob object. The type attribute indicates the MIME type of Blob. If it is an unknown type, an empty string is returned. The following code: select the file <input type = "file" id = "file" multiple size = "80" accept = "image/*"/> <input type = "button" onclick = "ShowFileType (); "value =" display file information "/> file Byte Length: <span id =" size "> </span> <br/> file type: <span id = "type"> </span> the JS Code is as follows:
Function ShowFileType () {var file = document. getElementById ("file "). files [0]; var size = document. getElementById ("size"); var type = document. getElementById ("type"); // display the size of the object's byte length. innerHTML = file. size; // display the file type. innerHTML = file. type; console. log (file );}
We print out the file, as shown in Figure 3. There are five methods for the FileReader object, four of which are used to read the file, and the other for reading the process interruption. Note that: no matter whether the read succeeds or fails, the method does not return the read result, but saves the result in the result attribute. This object is asynchronous. The method of FileReader object is as follows: readAsBinaryString (file): This method reads data from blob objects or files as binary strings. Generally, we send it to the server, the server can store files through this string. ReadAsText (file, encoding): Read the file in plain text format, save the read text in the result attribute, the second parameter is used to specify the encoding type, optional. ReadAsDataURL (file): Read the file and save it as a Data URL in the result attribute. ReadAsArrayBuffer (file): Read the file and save an ArrayBuffer containing the file content in the result attribute. The event of the FileReader object is as follows: onabort: onerror triggered when Data Reading is interrupted: onloadstart triggered when an error occurs in Data Reading: onprogress triggered when Data Reading starts: onload in data reading: onloadend is triggered when Data Reading is completed successfully. It is triggered when Data Reading is completed, whether it is successful or failed. Let's take a look at the demo to see how to use the first three methods in the FileReader object. Note: The data read by the fileReader object is saved in the result, as shown in the following code:
<P> <label> select a file: </label> <input type = "file" id = "file"/> <input type = "button" value = "read image" onclick = "readAsDataURL () "/> <input type =" button "value =" Read Binary data "onclick =" readAsBinaryString () "/> <input type =" button "value =" Read text file "onclick =" readAsText () "/> </p> <div id =" result "> </div>
The JS Code is as follows:
<Script> var result = document. getElementById ("result"); if (typeof FileReader = 'undefined') {result. innerHTML = "sorry, your browser does not support FileReader";} // read the file as a Data URL to the page function readAsDataURL () {// check whether the image type is var simpleFile = document. getElementById ("file "). files [0]; if (! /Image \/\ w + /. test (simpleFile. type) {alert ("Please make sure the file type is image type"); return false;} var reader = new FileReader (); // read the file into the page reader in the form of Data URL. readAsDataURL (simpleFile); reader. onload = function (e) {console. log (this. result); result. innerHTML = '';} // read the file in binary form into the page function readAsBinaryString () {// check whether the file is of the image type var simpleFile = document. getElementById ("file "). files [0]; If (! /Image \/\ w + /. test (simpleFile. type) {alert ("Please make sure the file type is image type"); return false;} var reader = new FileReader (); // read the file into the page reader in binary format. readAsBinaryString (simpleFile); reader. onload = function (e) {// display the result of binary data on the page. innerHTML = this. result ;}}// read the file into the page in text format: function readAsText () {var simpleFile = document. getElementById ("file "). files [0]; var reader = new FileReader (); // read the file into the reader on the page as text. readAsText (simpleFile); reader. onload = function (e) {result. innerHTML = this. result ;}}</script>
The above code can be copied to the text editor for demonstration. You can preview the code and it will not be available here. However, the above Code is not supported in safari ~ The btoa and atob methods are in HTML5. The btoa and atob methods support base64 encoding. B can be considered as a string of binary data, a can be understood as an ASCLL string. btoa is used as follows: var result = window. btoa (data); this method is used to encode a string with base64 encoding. This method uses a parameter that is a Unicode string consisting of a string of binary data, this method returns the encoded base64 string. The atob method is as follows: var result = window. atob (data); this method is used to decode a string encoded in base64 format. This method uses a parameter, the parameter value is a base64 encoded string, and the method returns a decoded Unicode string consisting of binary data. The browser supports: firefox, chrome, when does opera10.5 + and IE10 + use the btoa method? When the server database directly saves the binary data of the image and the format of the image file, it is very useful when we need to render the Image Based on the binary data; the following code:
<P> <label> select a file: </label> <input type = "file" id = "file"/> <input type = "button" value = "read image" onclick = "readPicture () "id =" btnReadPicture "/> </p> <div id =" result "> </div>
The JS Code is as follows:
If (typeof FileReader = 'undefined') {result. innerHTML = "sorry, your browser does not support FileReader";} function readPicture () {// check whether it is of the image type var simpleFile = document. getElementById ("file "). files [0]; if (! /Image \/\ w + /. test (simpleFile. type) {alert ("Please make sure the file type is image type"); return false;} var reader = new FileReader (); // read the file as a binary file into reader on the page. readAsBinaryString (simpleFile); reader. onload = function (f) {var result = document. getElementById ("result"); var src = "data:" + simpleFile. type + "; base64," + window. btoa (this. result); result. innerHTML = ' ';}}
When selecting an image, click the read image button to generate an image. Although we can use the readAsDataURL method described above, we can also directly read the image, however, if the server directly stores binary files, we can directly use btoa to generate images. Below we can see the atob demo as follows: we can use canvas to draw an image. After clicking the upload image button, we first obtain the url of the image through the toDataURL () method of the canvas element, finally, obtain the base64 string in the URL address, use the atob method to decode it into a string of binary data, and submit the binary data to the server. The following code: <input type = "button" value = "Upload image" onclick = "imgSave () "/> <br/> <canvas id =" canvas "width =" 400 "height =" 300 "> </canvas> the JS Code is as follows:
<script> var canvas; function draw(id) { canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = 'rgb(0,0,255)'; context.fillRect(0,0,canvas.width,canvas.height); context.fillStyle = 'rgb(255,255,0)'; context.fillRect(10,20,50,50); } draw('canvas'); function imgSave(){ var data = canvas.toDataURL("image/png"); data = data.replace("data:image/png;base64,",""); var xhr = new XMLHttpRequest(); xhr.open("POST","uploadImg.php"); xhr.send(window.atob(data)); }</script>
UploadImg. php write by yourself; Next we will make a preview of the local image before uploading, but safari does not support it, so it may not be good for mobile users, especially in IOS6, there should be other solutions to solve this problem. Let's take a look at Baidu's plug-in. The URL is as follows: today, to learn FileReader, let's take a look at it. If you have uploaded a local image for preview, IE10 + is not supported, and there will be a bug when placing the page on the server side under IE, as shown below: As shown above, this method document under IE. selection. createRange () is not supported. Therefore, in order to fix this bug and make it more than IE10, we have made a special research today to get the document focus under the file control. selection. createRange () will reject access, so we need to lose the focus. We can add a code to support file. for blur (); IE10 + bugs, we can use the File API described above in html5. first, we can determine whether it is IE. If it is, and if it is less than 10, the filter method is used to solve the problem of Image Upload. If it is another browser, the html5 File Upload method is used. However, safari does not handle the problem well, the reason is that safari does not support html5 fileReader APIs. Therefore, if you want to develop images on mobile terminals that are compatible with IOS6 and 6 +, note that this feature is not supported ~ Of course, if you have a better solution to support IOS6, please leave a message and you can summarize it and learn it together ~ V. demo of preview effect before uploading an image (incompatible with Safari) 1. in a standard browser (IE10 +), you can use the File API in HTML5 to preview the uploaded image. Here there are 2 solutions to solve the problem. The first method is to use the file API, as shown in the following code:
function html5Reader(file) { var file = file.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e){ var pic = document.getElementById("img"); pic.src=this.result; }}
2. the second solution is to use URL. createObjectURL (fileObj) method and canvas technology. Let's take a look at the support for this URL. for details about the browser of createObjectURL (fileObj), click the following link: The implementation code is as follows:
function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataURL = canvas.toDataURL("image/"+ext); return dataURL; }
The HTML code is as follows: <input type = "file" id = "logo" name = "logo" accept = "image/*"> <div id = "btn" style = "margin-top: 50px; font-size: 40px; "> btn </div> <canvas id =" myCanvas "> </canvas> All JS Code is as follows:
<Script> var EventUtil = {addHandler: function (element, type, handler) {if (element. addEventListener) {element. addEventListener (type, handler, false);} else if (element. attachEvent) {element. attachEvent ("on" + type, handler);} else {element ["on" + type] = handler ;}}; var btn = document. getElementById ("btn"); var pic = document. getElementById ("img"); function getBase64Image (img) {var canvas = e Nt. createElement ("canvas"); canvas. width = img. width; canvas. height = img. height; var ctx = canvas. getContext ("2d"); ctx. drawImage (img, 0, 0, img. width, img. height); var ext = img. src. substring (img. src. lastIndexOf (". ") + 1 ). toLowerCase (); var dataURL = canvas. toDataURL ("image/" + ext); return dataURL;} var ua = navigator. userAgent. toLowerCase (); EventUtil. addHandler (btn, 'click', function () {var file = Document. getElementById ("logo"); var ext = file. value. substring (file. value. lastIndexOf (". ") + 1 ). toLowerCase (); // if (ext! = 'Png '& ext! = 'Jpg '& ext! = 'Jpeg ') {alert ("the image format must be png, jpg, or jpeg! "); Return;} if (/msie ([^;] + )/. test (ua) {var lowIE10 = RegExp ["$1"] * 1; if (lowIE10 = 6) {// you can directly display the image file by setting the src of img as the local path in IE 6. select (); // document when the focus is obtained under the file control. selection. createRange () will reject access, so we need to lose the focus. File. blur (); var reallocalpath = document. selection. createRange (). text; pic. src = reallocalpath;} else if (lowIE10> 6 & lowIE10 <10) {// IE7 ~ 9 IE10 + processes the file according to html5 standards. select (); // document when the focus is obtained under the file control. selection. createRange () will reject access, so we need to lose the focus. File. blur (); var reallocalpath = document. selection. createRange (). text; // for IE of non-IE6 versions, setting the img src directly due to security issues cannot display local images, but the pic can be implemented through filters. style. filter = "progid: DXImageTransform. microsoft. alphaImageLoader (sizingMethod = 'image', src = \ "" + reallocalpath + "\")"; // set the src of img to a base64 encoded transparent image to cancel displaying the default image pic of the browser. src = 'data: image/gif; base64, R0lGODlhAQABAIAAAP // encode = ';} else if (lowIE10 >=10) {html5Reader (file );}} else {html5Reader (file) ;}}); function html5Reader (file) {var fileObj = file. files [0], img = document. getElementById ("img"); // URL. createObjectURL safari does not support img. src = URL. createObjectURL (fileObj); img. onload = function () {var data = getBase64Image (img); console. log (data); // print the base64 encoding}/* var file = file. files [0]; var reader = new FileReader (); reader. readAsDataURL (file); reader. onload = function (e) {var pic = document. getElementById ("img"); pic. src = this. result;} */} </script>