JS implementation of Image upload preview function, using Base64 encoding to achieve
There are many ways to achieve image upload, here we introduce a relatively simple one, using Base64 to encode image information, and then directly to the image of the base64 information to the database.
However, it is not recommended to use this method for many images that need to be uploaded in the system, we usually choose the way to save the image path, which helps to reduce the database pressure, base64
The encoded picture information is a very long string, generally we use the Longtext type to store it in the database.
The HTML code is as follows:
<div class= "Col-sm-6" >
<input type= "File" id= "Headportraitupload" style= "margin-top:10px;" >
</div>
The JavaScript code is as follows:
$ ("#headPortraitUpload"). On ("Change", Headportraitlistener);
/* Define global variables storage picture information */
var base64head= "";
/* Avatar upload monitor */
function Headportraitlistener (e) {
var img =document.getelementbyid (' headportraitimgshow ');
if (window. FileReader) {
var file = E.target.files[0];
var reader = Newfilereader ();
if (file&& file.type.match (' image.* ')) {
Reader.readasdataurl (file);
} else {
Img.css (' Display ', ' none ');
Img.attr (' src ', ');
}
Reader.onloadend =function (e) {
Img.setattribute (' src ', reader.result);
Base64head =reader.result;
}
}
}
Preview of Effect: Default picture-----
Finally, the Base64head submitted to the background to save the database, the next time from the database to be removed directly from the base64 information placed in the IMG tag src inside the picture back to show
Base64 upload picture to database