将图像 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>