JS Image to Base64

Source: Internet
Author: User


<input id="file" type="file">
<img id="img" style="max-height: 300px;">
<textarea id="textarea" style="width: 100%;height: 300px;"></textarea>

<script>
$("#file").change(function () {
Run(this, function (data) {
$(‘#img‘).attr(‘src‘, data);
$(‘#textarea‘).val(data);
});
});

Function run(input_file, get_data) {
/*input_file: file button object */
/*get_data: Method executed after successful conversion */
If (typeof (FileReader) === ‘undefined‘) {
Alert ("Sorry, your browser does not support FileReader, you can't convert images to Base64, please use modern browser!");
} else {
Try {
/ * Image to Base64 core code * /
Var file = input_file.files[0];
//Here we judge the type to return if it is not an image. You can upload any file if you remove it.
If (!/image\/\w+/.test(file.type)) {
Alert ("Please make sure the file is an image type");
Return false;
}
Var reader = new FileReader();
Reader.onload = function () {
Get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
Alert (‘Image to Base64 is wrong! ‘ + e.toString())
}
}
}

</script>

JS Image to Base64


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.