问题
I've got some problems about to fileinputjs.The images' src are blob.But i want to use images' src to do something.So i use readAsDataURL to get base64.But there are any problems about it 。
<script type="text/javascript">
$("#last").click(function(){
var blob=document.querySelector(".file-preview-image").src;
var reader = new FileReader(); //通过 FileReader 读取blob类型
reader.onload = function(){
this.result === dataURI; //base64编码
}
console.log(reader.readAsDataURL(blob));
})
</script>
Then there are Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
回答1:
A lot of misconception here.
- your variable
blobis not a Blob, but a string, the url of.file-preview-image.
FileReader can't do anything from this string. (Or at least not what you want). - in the
onloadcallback of the FileReader, you are just checking if the result is equal to an undefined variabledataURI. That won't do anything. - you are trying to
console.logthe call toreadAsDataURLwhich will beundefinedsince this method is asynchronous (you have to callconsole.login the callback).
But since I guess that what you have is an object url (blob://), then your solution is either to get the real Blob object and pass it to a FileReader, or to draw this image on a canvas, and then call its toDataURL method to get a base64 encoded version.
If you can get the blob :
var dataURI;
var reader = new FileReader();
reader.onload = function(){
// here you'll call what to do with the base64 string result
dataURI = this.result;
console.log(dataURI);
};
reader.readAsDataURL(blob);
otherwise :
var dataURI;
var img = document.querySelector(".file-preview-image");
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0,0);
dataURI = canvas.toDataURL();
But note that for the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.
Also, by default, it will convert your image to a png version. You can also pass image/jpegas the first parameter of toDataURL('image/jpeg') if the original image is in JPEG format.
If the image is an svg, then there would be an other solution using the <object> element, but except if you really need it, I'll leave it for an other answer.
来源:https://stackoverflow.com/questions/37130010/html-image-blob-to-base64