HTML5 preview local pictures

Time:2021-10-22

Problem description
Suppose we have a picture upload control in HTML:

Copy code

The code is as follows:

<input type=”file” name=”image” accept=”image/*” />

Note that this accept = “image / *” is very important. It specifies that the uploaded image will be related to the pop-up window selection type of the system at the mobile terminal. Be sure to add it.
Then, the question is, is there any way to read the content of the picture before we submit the form to the server?
It seems simple. All files are client files. It should be possible, but there was really no good way before. However, since HTML5, this function has come back. This function can be easily realized through FileReader.
Examples illustrate the problem

Copy code

The code is as follows:

$(function() {
$(‘#upload_image’).change(function(event) {
//Get the HTML5 JS object of the file according to this < input >
var files = event.target.files, file;
if (files && files.length > 0) {
//Get currently uploaded files
file = files[0];
//Let’s see what this object is on the console
console.log(file);
//Then we can do some actions such as file size verification
if(file.size > 1024 * 1024 * 2) {
Alert (‘picture size cannot exceed 2MB! ‘);
return false;
}
// !!!!!!
//The following is the key to generate an available image URL through this file object
//Get window URL tool
var URL = window.URL || window.webkitURL;
//Generate target URL through file
var imgURL = URL.createObjectURL(file);
//Use this URL to generate a < img > and display it
$(‘body’).append($(‘<img/>’).attr(‘src’, imgURL));
//Use the following sentence to release the servo of this URL in memory. After running, the URL will be invalid
// URL.revokeObjectURL(imgURL);
}
});
});

Brief description
In short, the whole operation is designed as follows:
1. Trigger the event through the change event of < File >, and obtain the event object;
2. Obtain the JS object file of the uploaded file through the event object;
3. Generate an available URL from the file object through the window.url tool;
4. Put this URL into use;
5. * release the servo of this URL
Key points:
1. For the same file, each time the url.createobjecturl is called, a different URL will be regenerated;
2. When calling url.createobjecturl, the browser will automatically open up space in memory to serve the URL, that is, make the URL successful;
3. If url.revokeobjecturl (imgurl) is called; After that, the servo will be turned off, and then the URL will be 404;
4. All this is the business of the client, and the server knows nothing about it, including the diagram you choose;
5. The imgurl looks like this: blob: http% 3A / / localhost% 3a8000 / 22cc97d5-5e46-4d87-9df4-c3e8c0aa72bb