Convert image URL to File instance
P粉121447292
P粉121447292 2023-09-04 14:58:36
0
1
403
<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>
P粉121447292
P粉121447292

reply all(1)
P粉680087550

To create the file (I'm not sure why you need it), you need to pass in the binary data

https://developer.mozilla.org/en -US/docs/Web/API/File/File

This is a file in memory. You cannot read it from disk. You cannot write it to disk. I guess you can set it to a value and send it as FormData.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!