图像 url 到 file() 对象使用 js

Tra*_*nns 4 javascript vue.js quasar

对于我的 vue 应用程序中的注册模块,我让用户在表单中上传图像。我将这些图像上传到我的存储中,并在注册中保存了这张照片的下载 url。编辑注册时,我需要从存储中取出照片,这很简单,因为我得到了 url。但我需要它是一个 file() 对象。我找到了将它变成 blob 的方法,但它需要是一个文件。我怎样才能做到这一点?

小智 11

它可以通过请求一个 blob 并生成一个 File 对象来完成。有必要指定 blob 的 MIME 类型。

const urlToObject= async()=> {
  const response = await fetch(image);
  // here image is url/location of image
  const blob = await response.blob();
  const file = new File([blob], 'image.jpg', {type: blob.type});
  console.log(file);
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案的问题是,在获取映像时,您可能会受到 CORS 策略的阻止。 (12认同)

Sam*_*eph 0

由于您让用户上传文件,因此您已经将该文件作为File对象。

但是,如果您想将其转换为 blob 进行一些编辑并将其转换回对象File,则可以使用File()构造函数将 blob 转换为文件。

const file = new File([blob], "imagename.png");

另请注意,File() 构造函数采用 Blob 数组作为参数,而不是单个 Blob。