最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i read data from blob url? - Stack Overflow

programmeradmin7浏览0评论

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?

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?

Share Improve this question asked Nov 25, 2019 at 10:12 OrElseOrElse 10k40 gold badges149 silver badges265 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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);
}
发布评论

评论列表(0)

  1. 暂无评论