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

标签 javascript file url blob firebase-storage

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

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

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

最佳答案

尝试使用 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>

截至 2022 年 7 月,fetch API 有大约 97% browser support在全局范围内,基本上只有 IE 缺少它。您可以使用 polyfill 使其接近 100% ,如果您仍然以 IE 为目标,我建议您使用它。

关于javascript - 如何从 JavaScript 中的 URL 获取 File() 或 Blob()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44070437/

相关文章:

javascript - 使用 OOP 编写 jQuery 插件

javascript - 我如何使用 JavaScript 确定屏幕阅读器将读取的内容?

java - 使用 Javascript 将 java.util.List 与下拉列表绑定(bind)

Android 使用其 URL 检查文件是否存在于远程服务器中

javascript - 剑道网格增删改查 : how make update

linux - Linux下C语言如何获取文件长度?

java - [Java with Docker-compose] : java. io.FileNotFoundException :/var/lib/data/17. txt (没有这样的文件或目录)

android - 如何以编程方式写入 Android 中的 DocumentFile?

http - 如何在 URL 被 http 包处理之前重写它

javascript - W3C 兼容 URL 的正则表达式?