將圖像 URL 轉換為 File 實例
<p>我有圖像資料數組,並嘗試將其轉換為<code>檔案</code>數組</p>
<pre class="brush:php;toolbar:false;">const images = [
{ img: "http://localhost/images/1.jpg", name: "1.png", mime_type: "image/jpeg" },
{ img: "http://localhost/images/2.jpg", name: "2.png", mime_type: "image/jpeg" },
]
const res: File[] = images.map(function (item) {
return new File([item.img], item.name, { type: item.mime_type })
})</pre>
<p>這不起作用:(據我了解,base24 中轉換後的映像應該傳遞給檔案建構函式?我該怎麼做?</p>
<p>更新:
我有一個 VUE 組件來處理圖像。輸入組件具有數組類型的屬性。如何根據資料庫傳回的資料建立數組。從資料庫返回:圖像連結、名稱和類型。 </p>
<p>UPD2答案:</p>
<pre class="brush:php;toolbar:false;">let PhotosAsFile: File[] = []
const _photos = [
{ url: "http://localhost:8080/images/1.jpeg", name: "name1", mime_type: "image/jpeg" },
{ url: "http://localhost:8080/images/2.jpeg", name: "name2", mime_type: "image/jpeg" },
{ url: "http://localhost:8080/images/3.jpeg", name: "name3", mime_type: "image/jpeg" },
]
const data: Promise<File>[] = _photos.map(async function (item): Promise<File> {
const myBlob: Blob = await getBlobFromUrl(item.url)
const extensionsFile: RegExpMatchArray | null | undefined = item.url?.match(/\.([^.] )$/)
return new File([myBlob], extensionsFile && item.name ? item.name "." extensionsFile[1] : "image.jpeg", {
type: item.mime_type ?? "image/jpeg",
})
})
Promise.all(data).then((values: File[]): void => {
PhotosAsFile = values
})
const getBlobFromUrl = (url): Promise<Blob> => {
return new Promise((resolve, reject): void => {
const request: XMLHttpRequest = new XMLHttpRequest()
request.open("GET", url, true)
request.responseType = "blob"
request.onload = () => {
resolve(request.response)
}
request.onerror = reject
request.send()
})
}</pre></p>