JS implementation of Image upload preview function, using Base64 encoding to achieve

Source: Internet
Author: User

Tags: images submit decimal Top base64 encoded monitor height color change

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: