Home >Web Front-end >JS Tutorial >How to Convert an Object URL to a Blob or File for FormData?
Retrieving Files or Blobs from Object URLs
When allowing users to upload images through drag-and-drop or other methods, the use of URL.createObjectURL is employed to generate object URLs for image display. Since these URLs are intended for reuse, they need not be revoked. However, when the need arises to create a FormData object that can accept one of these images as part of a form upload, challenges arise in converting the object URL back to a Blob or File for inclusion in the FormData.
Modern Solution:
Leveraging the capabilities of modern browsers, we can utilize the fetch() API to retrieve the file or blob associated with an object URL. The following code block demonstrates this technique:
<code class="javascript">let blob = await fetch(url).then(r => r.blob());</code>
This solution works seamlessly with both object URLs and regular URLs. Once the blob is obtained, it can be appended to the FormData object, enabling the inclusion of the image in the form submission.
The above is the detailed content of How to Convert an Object URL to a Blob or File for FormData?. For more information, please follow other related articles on the PHP Chinese website!