在我的Vue应用程序的注册模块中,我允许用户在表单中上传图像。我将这些图像上传到存储中,并将该照片的下载URL保存在注册表中。在编辑注册表时,由于我拥有该URL,所以需要从存储中获取图片。但是我需要它成为一个file()对象。我已经找到了将其转换为blob的方法,但它需要成为一个文件。我该怎么办?
在我的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);
}
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)
})
})
})
由于您允许用户上传文件,因此您已经将文件作为File
对象。
但是,如果您想将其转换为Blob以进行一些编辑并将其转换回File
对象,则可以使用File()
构造函数将Blob转换为File。
const file = new File([blob], "imagename.png");
另外,请注意,File()构造函数接受Blob数组作为参数,而不是单个Blob。