[英]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.