Convert image URL to File instance
<p>I have an array of image data and am trying to convert it to a <code>file</code>array</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>This doesn't work :(As I understand it, the converted image in base24 should be passed to the file constructor? How do I do that?</p>
<p>Update:
I have a VUE component that handles images. The input component has a property of type array. How to create an array based on the data returned by the database. Returns from database: image link, name and type. </p>
<p>UPD2 answer: </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>