<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