【问题标题】:How can i read data from blob url?如何从 blob url 读取数据?
【发布时间】:2020-03-20 14:30:23
【问题描述】:

我必须将数据作为字符数组读取,或者更好地作为来自 blob url 的 base64 字符串读取, 供以后处理。

例如,我必须阅读的blobUrlblob:https://localhost:44399/a4775972-6cc8-41a3-af64-1180d9941ab0

实际上,当点击链接时,文件会在我的浏览器中预览。

在尝试读取文件时

var blobUrl = document.getElementById("test").value;

var reader = new FileReader();
reader.readAsDataURL(blobUrl);
reader.onloadend = function ()
{
   base64data = reader.result;
   console.log(base64data);
}

我得到了错误

Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

我在这里做错了什么?

readAsDataURL 实际上不接受 url 作为输入?

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery blob filereader bloburls


    【解决方案1】:

    正如spec 所说,readAsDataURL 仅接受 Blob(即 File 继承者)作为参数。

    因此您需要使用原始 blob 文件引用(如果有)或将 URL 转换为文件实例。

    要将图像 URL 转换为文件本身,您可以执行以下操作。

    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);
      ...
    }
    

    或者,如果您的标记中有用于上传文件的输入(这是一种流行的用例),您可以直接获取文件参考。

    var file = document.querySelector('input[type=file]').files[0];
    var reader = new FileReader();
    
    if (file) {
      reader.readAsDataURL(file);
    }
    

    【讨论】:

    • 感谢您的努力。我得到 response.blob 不是函数
    • @OrElse 因此很可能您传递了错误的 URL 格式来获取。请参阅此 fetch.spec.whatwg.org/#url 并提供带有 blob 前缀的 URL。
    • 顺便说一句,如果在您的情况下用户使用 标签上传文件,您可以直接获取文件实例。再次检查我的答案,我更新了它。
    • 进行了适当的更改,但我得到了同样的错误。参数 1 不是“Blob”类型。调试后 convertToFile 方法包含 blob = Promise {} (我不使用输入文件进行上传)实际上blob url是通过javascript从ajax响应创建的
    • 对,由于convertToFile是异步函数,解决后需要等待。我会尽快用添加的示例更新我的答案
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 2016-06-10
    • 2018-10-02
    • 2011-08-06
    • 2013-02-21
    • 2019-11-17
    • 2016-12-22
    • 2011-04-14
    相关资源
    最近更新 更多