Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-29 22:30:03
Original
470 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
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!