简体   繁体   English

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

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

For a registration module in my vue app I let users upload images in a form.对于我的 vue 应用程序中的注册模块,我让用户在表单中上传图像。 I upload these images to my storage and save the download url of this photo in the registration.我将这些图像上传到我的存储中,并在注册中保存了这张照片的下载 url。 When editing a registration I need to get the photo's out of the storage which is simple since I got the url.编辑注册时,我需要从存储中取出照片,这很简单,因为我得到了 url。 But I need it to be a file() object.但我需要它是一个 file() 对象。 I have found ways to turn it into a blob but it needs to be a file.我已经找到了将它变成 blob 的方法,但它需要是一个文件。 How can I do this?我怎样才能做到这一点?

It can be done by requesting a blob and generating a File object.它可以通过请求一个 blob 并生成一个 File 对象来完成。 It is necessary to specify the MIME type of the blob.有必要指定 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);
}

Since you are letting the user upload a file, you already have the file as a File object.由于您让用户上传文件,因此您已经将该文件作为File对象。

But if you wanna convert it to a blob for making some edits and convert it back to a File object, you can use the File() constructor for converting a blob to a File.但是,如果您想将其转换为 blob 以进行一些编辑并将其转换回File对象,则可以使用File()构造函数将 blob 转换为 File。

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

Also, notice that the File() constructor takes an array of blobs as argument and not a single blob.另外,请注意 File() 构造函数将一个 blob 数组作为参数而不是单个 blob。

The ES6 way, with Promise : 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