Home >Web Front-end >JS Tutorial >How to Convert an Object URL to a Blob or File for FormData?

How to Convert an Object URL to a Blob or File for FormData?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 22:30:03539browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn