Home >Web Front-end >JS Tutorial >Example of local preview before Javascript image upload_javascript skills
The image upload preview function is mainly used to preview an effect before the image is uploaded. The current mainstream methods mainly include js, jquery and flash, but we generally use js to implement the image upload preview function. Let’s take a look at one example.
Principle:
It is divided into two steps: when the input of uploading the image is triggered and the local image is selected, obtain the URL of the object of the image to be uploaded (object URL); assign the object URL to the src attribute of the pre-written img tag. Show the picture.
Here, we need to understand the File object, Blob object and window.URL.createObjectURL() method in Javascript.
File object:
File object can be used to obtain information about a file, and can also be used to read the contents of this file. Usually, the File object is the FileList object returned after the user selects a file on an input element, or it can It comes from the DataTransfer object generated by drag and drop operation.
Let’s look at getting the FileList object:
Blob object:
A Blob object is a file-like object containing read-only raw data. The data in the Blob object does not necessarily have to be in the native form in JavaScript. The File interface is based on Blob, inherits the functions of Blob, and extends support A local file on the user's computer.
The object URL we want to get is actually obtained from the Blob object, because the File interface inherits Blob. Let’s convert the Blob object into a URL:
Compatibility:
The above method is applicable to chrome browser
If it is IE browser, you can directly use the input value instead of src
To view information online, you can directly use the getAsDataURL() method of the File object to obtain the URL. Now this method All have been abolished. Similar methods include getAsText() and getAsBinary(). Let's take a look at such an example.
This code is to get the complete path of the client image
We will limit its size and format
Among them, loadFile is the id of the html input file. In its change event, that is, after selecting the file to be uploaded, do you want the image to be displayed in the picture box? Add the following code at the end of the above code
Since jQuery is used, let’s share an example of code written with jQuery: