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

Sam*_*Sam 14 javascript url blob file firebase-storage

我尝试通过网址(带ref().put(file))(www.example.com/img.jpg)将图片上传到Firebase存储空间.

要做到这一点,我需要一个文件或Blob,但每当我尝试new File(url)它时说"没有足够的论点"......

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

Jam*_*aus 33

尝试使用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)
});
Run Code Online (Sandbox Code Playgroud)
<div id="myImg"></div>
Run Code Online (Sandbox Code Playgroud)

截至2018年4月,fetch API在全球范围内拥有约88%的浏览器支持,基本上只是IE缺少它.您可以使用polyfill将其提高到接近100%,如果您仍然以IE为目标,我建议您使用polyfill.

  • res.blob() 返回一个承诺,因此我们需要等待它解析后再访问内容:https://developer.mozilla.org/en-US/docs/Web/API/Body/blob (2认同)

Rua*_*los 5

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

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

  • 这不是一个纯 javascript 解决方案,而是一个 jQuery 解决方案,您绝对应该在答案中提及这一点。 (13认同)