Base64 Upload image to database

Source: Internet
Author: User
Tags base64

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

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.