如何从 javascript 中的 URL 获取 File() 或 Blob()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44070437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:19:29  来源:igfitidea点击:

How to get a File() or Blob() from an URL in javascript?

javascriptfileurlblobfirebase-storage

提问by Sam

I try to upload an image to the Firebase storage from an URL (with ref().put(file))(www.example.com/img.jpg).

我尝试从 URL(带有ref().put(file))(www.example.com/img.jpg)将图像上传到 Firebase 存储。

To do so i need a File or Blob, but whenever I try new File(url)it says "not enough arguments“…

为此,我需要一个文件或 Blob,但每当我尝试时,new File(url)它都会说“参数不足”......

EDIT: And I actually want to upload a whole directory of files, that's why i can't upload them via Console

编辑:我实际上想上传整个文件目录,这就是我无法通过控制台上传它们的原因

回答by James Kraus

Try using the fetch API. You can use it like so:

尝试使用fetch API。你可以像这样使用它:

fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
  .then(res => res.blob()) // Gets the response and returns it as a blob
  .then(blob => {
    // Here's where you get access to the blob
    // And you can use it for whatever you want
    // Like calling ref().put(blob)

    // Here, I use it to make an image appear on the page
    let objectURL = URL.createObjectURL(blob);
    let myImage = new Image();
    myImage.src = objectURL;
    document.getElementById('myImg').appendChild(myImage)
});
<div id="myImg"></div>

As of May 2020, the fetch API has about 95% browser supportworldwide, with basically just IE missing it. You can get that to near 100% using a polyfill, which I recommend if you're still targeting IE.

截至 2020 年 5 月,fetch API 在全球范围内拥有约95% 的浏览器支持,基本上只有 IE 缺少它。您可以使用polyfill使其接近 100% ,如果您仍然针对 IE,我建议您这样做。

回答by Ruan Carlos

@James answer is correct but it is not compatible with all browsers. You can try this jQuery solution :

@James 答案是正确的,但它与所有浏览器都不兼容。你可以试试这个 jQuery 解决方案:

$.get('blob:yourbloburl').then(function(data) {
  var blob = new Blob([data], { type: 'audio/wav' });
});

回答by stanimirsp

It did not work until I added credentials

直到我添加凭据它才起作用

fetch(url, {
      headers: {
        "Content-Type": "application/octet-stream",
      },
      credentials: 'include'
 })