This article describes how to preview local images in HTML5. If you need some help, refer to the Problem description.
Suppose we have an Image Upload control in HTML:
The Code is as follows:
Note that this accept = "image/*" is very important. It specifies the image to be uploaded and is associated with the pop-up window selection type of the system at the mobile end.
Then, the question is, can we read the image content before submitting this form to the server?
It seems simple. All files are client files. It should be okay, but there is no good way to do it before. However, since HTML5 is available, this function has come back, fileReader allows you to easily implement this function.
Example
The Code is as follows:
$ (Function (){
$ ('# Upload_image'). change (function (event ){
// Based on thisObtain the HTML5 js object of a file
Var files = event.tar get. files, file;
If (files & files. length> 0 ){
// Obtain the currently uploaded file
File = files [0];
// You can view the object in the console.
Console. log (file );
// You can check the file size.
If (file. size> 1024*1024*2 ){
Alert ('the image size cannot exceed 2 MB! ');
Return false;
}
//!!!!!!
// The following is the key. An available image URL is generated through this file object.
// Obtain the window URL Tool
Var URL = window. URL | window. webkitURL;
// Generate the target url through file
Var imgURL = URL. createObjectURL (file );
// Use this URL to generate one to display it
$ ('Body'). append ($ (''). attr ('src', imgURL ));
// Use the following sentence to release the servo of this url in the memory. After the URL is run, it will be invalid.
// URL. revokeObjectURL (imgURL );
}
});
});
Brief Description
The entire operation is designed as follows:
1. Pass And get the event object;
2. Get the js object file of the uploaded file through the event object;
3. Use the window. URL tool to generate an available URL from the file object;
4. Place the URL for use;
5. * release the servo of this URL
Key points:
1. For the same file, each time you call URL. createObjectURL, a different URL is generated;
2. When the URL. createObjectURL is called, the browser automatically opens up space in the memory for Servo the URL, that is, making the URL request successful;
3. If URL. revokeObjectURL (imgURL) is called, The servo will turn it off and 404 will be requested for this URL;
4. This is all about the client. The server knows nothing about this, including the picture you choose;
5. This imgURL looks like this: blob: http % 3A // localhost % 3A8000/22cc97d5-5e46-4d87-9df4-c3e8c0aa72bb