繁体   English   中英

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

[英]image url to file() object using js

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

它可以通过请求一个 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);
}

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

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

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

另外,请注意 File() 构造函数将一个 blob 数组作为参数而不是单个 blob。

ES6 方式,使用 Promise

const blobUrlToFile = (blobUrl:string): Promise<File> => new Promise((resolve) => {
    fetch(blobUrl).then((res) => {
      res.blob().then((blob) => {
        // please change the file.extension with something more meaningful
        // or create a utility function to parse from URL
        const file = new File([blob], 'file.extension', {type: blob.type})
        resolve(file)
      })
    })
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM