I have to read the data as an array of characters or even better as an base64 string from a blob url, for later processing.
The blobUrl
that i have to read for example is
blob:https://localhost:44399/a4775972-6cc8-41a3-af64-1180d9941ab0
Actually when following the link, the file is previewed in my browser.
While trying to read the file
var blobUrl = document.getElementById("test").value;
var reader = new FileReader();
reader.readAsDataURL(blobUrl);
reader.onloadend = function ()
{
base64data = reader.result;
console.log(base64data);
}
I get the error
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
What am i doing wrong here?
readAsDataURL
does not actually accept url as input?
How can i fix that?
As spec says, readAsDataURL
accept Blob only (which is File inheritor) as a param.
So you need to use original blob file reference (if you have it) or convert URL into file instance.
To convert image URL into the file itself, you can do the following.
async function convertToFile(url){
let response = await fetch(url);
let blob = await response.blob();
return new File([blob], 'put_the_name.jpg', {
type: 'image/jpeg'
});
}
// usage
async function main() {
const url = document.getElementById("test").value; // get file URL somehow
const file = await convertToFile(url); // usage of function above
const reader = new FileReader();
reader.readAsDataURL(file);
...
}
Or if you have an input in your markup for uploading files (which is popular use case), you can get file reference directly.
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}