Recently, I am working on an H5 project, which involves the function of taking pictures and uploading pictures and the function of identifying pictures. I will not elaborate on the function of identifying pictures here and it is not included in the scope of this article. After I finished and launched the project, my colleague asked me whether I could choose to upload multiple images at the same time. When I was doing it, I had no way to call the camera of my phone to take pictures if I added multiple attributes to the file form. If I didn't add it, I couldn't select multiple images at the same time. So I told my colleague the situation as it was. But when I think back, a single picture can be uploaded, but what about multiple pictures? So the content of this article is found.
HTML5 defines FileReader as an important member of the file API for reading files. According to W3C definition, the FileReader interface provides a method for reading files and an event model containing the read results.
The FileReader instance has 4 methods, 3 of which are used to read files and the other is used to interrupt reading. The following table lists these methods and their parameters and functions. It should be noted that the method does not return the read result regardless of the read success or failure, which is stored in the result attribute.
Method name | parameter | describe |
---|---|---|
abort | none | Interrupt read |
readAsBinaryString | file | Read the file as binary code |
readAsDataURL | file | Read the file as a DataURL |
readAsText | file, [encoding] | Read the file as text |
readAsText: This method has two parameters, the second parameter is the encoding method of the text, and the default value is UTF-8. This method is very easy to understand. Read the file in text, and the result of reading is the content in this text file.
readAsBinaryString: This method reads the file as a binary string, which we usually pass to the backend, through which the backend can store the file.
readAsDataURL: This is a method used in an example program. This method reads the file as a string starting with data:. The essence of this string is Data URL. Data URL is a solution to embed small files directly into documents. The small files here usually refer to files in formats such as images and html.
FileReader also contains a complete set of event models to capture the state of the file when reading it. The following table summarizes these events.
event | describe |
---|---|
onabort | Triggered when interrupted |
onerror | Triggered when an error occurs |
onload | Triggered when file read completes successfully |
onloadend | Read completion trigger, whether successful or failed |
onloadstart | Triggered at the start of the read |
onprogress | Reading |
Once the file starts reading, the result attribute of the instance will be populated regardless of success or failure. If the reading fails, the value of result is null, otherwise it is the result of the reading. Most programs will grab this value when successfully reading the file.
After understanding the FileReader provided by H5, we use FileReader to enable colleagues to select multiple images and upload them.
First, add a file form to HTML and set it to multiple (when the browser parses multiple, disabled, checked, selected properties, etc., as long as these properties exist, the default will be parsed to true, no matter if you set disabled=true, disabled=false or disabled="", if you don't want these properties to work, you can only use js to remove these properties unless you don't set these properties.), and set accept="image/*" to select files that can only select image types. The code is as follows:
<input type="file" accept="image/*" name="upload" multiple> <input type="hidden" /> <!--This hidden domain is set to facilitate storage of the image address returned after uploading to the server.-->
Next, it's JS to play:
//Upload picturesvar file = { upload: function (e) { var self = this; var files = ; var type = files[0].('/')[0]; if (type != 'image') { alertMsg('Please upload the picture'); return; } //var size = ( / 1024 / 1024); //if (size > 3) { // alert('The image size must not exceed 3M'); // return; //}; for (var i = 0; i < ; i++) { var reader = new FileReader(); (files[i]); = function () { //Aim to add some events or effects before uploading, such as loading... }; = function (e) { var dataURL = ; var imaged = new Image(); = dataURL; = function () { //Use canvas to compress the image var canvas = ('canvas'); var ctx = ('2d'); var w = 0; var h = 0; if ( > ) { h = 1000; var scale = / ; h = h > ? : h; w = h * scale; } else { w = 1000; var scale = / ; w = w > ? : w h = w / scale; } var anw = ("width"); var anh = ("height"); if ( > ) { = h; = w; } else { = w; = h; } (anw); (anh); if ( > ) { (h, 0); (90 * / 180) (this, 0, 0, w, h); (); } else { (this, 0, 0, w, h); } dataURL = ('image/jpeg'); //Callback function is used to submit data to the database (dataURL); }; }; } }, event: function () { $("#upload").change(function (e) { (e); }); }, callback: function (dataURL) { $. = false; // Here you must change the asynchronous ajax to synchronously to take out the image address returned and saved in the hidden domain and add it to the address bar as a parameter and pass it to the next page. The purpose of this is because the returned image address is not a json array, but a single json string, so you can only splice the returned image address json string together as parameters and pass it to the next page. $.post(url, dataURL, function (res) { //Convert the image of the base64 image stream into a normal image path through the background and upload it to the server var imgUrl = $("#hiddenImgUrl").val(); if () { $(".loading").hide(); if (imgUrl != "") { $("#hiddenImgUrl").val(imgUrl + "|" + ); //Add one in the middle is to facilitate the conversion of the passed image address parameters into an array to the next page } else { $("#hiddenImgUrl").val(); } var imgUrl = $("#hiddenImgUrl").val(); = "?imgUrl=" + imgUrl; } else { alert(); } }, "json"); }, init: function () { (); } } ();
Since I used synchronization when uploading to the server through post, I was unable to realize the loading animation effect during the process of writing the project, and put the loading animation effect in the method still did not work. In the end, I could only put it in the $("#upload").change(function (e) {}) method, the code is as follows:
event: function () { $("#upload").change(function (e) { $(".loading").show(); (e); }); }
The above is to upload multiple pictures at the same time and pass them to the next page to continue the subsequent operations. So how do you preview these pictures on this page after uploading multiple pictures at the same time? In fact, the method is also very simple. The return value of $.post in the callback function above contains the image paths uploaded to the server. Assign these paths to the src of the img tag, and then insert them into the page. The code is OK. The code is as follows:
callback: function (dataURL) { $.post(url, dataURL, function (res) { //Convert the image of the base64 image stream into a normal image path through the background and upload it to the server if () { $(".loading").hide(); var result = '<div class="result"><img src="'++'" alt=""/></div>'; var div = ('div'); = result; (div); } else { alert(); } }, "json"); }
Since there is no need to jump when previewing the picture, the path of all returned pictures does not need to be passed as parameters, so there is no need to set ajax asynchronously to synchronously.
The above is the JS mobile terminal/H5 introduced to you. Select multiple pictures to upload and use canvas to compress the pictures. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!