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:
<Divclass= "Col-sm-6"> <imgID= "Headportraitimgshow"src= "Img/defaultheadpoint.jpg"alt=""width= "160px"Height= "180px" /> <inputtype= "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 = new FileReader (); 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
JS implementation of Image upload preview function, using Base64 encoding to achieve