Retrieving a File or Blob from an Object URL
When working with images in a web application, it's common to use drag-and-drop or other methods to allow users to upload files. To display these images, URL.createObjectURL is typically used to convert them into object URLs. However, when it comes to submitting these images as part of a form, the question arises: how can you convert these object URLs back into a File or Blob and append them to a FormData object?
Modern Solution
Modern browsers provide a simple and efficient solution:
<code class="javascript">let blob = await fetch(url).then(r => r.blob());</code>
This code can be used to fetch a File or Blob from both object URLs and regular URLs. The URL parameter can be the object URL created earlier.
Once you have the Blob, you can easily append it to a FormData object and submit the form. Here's an example:
<code class="javascript">// Assume you have the Blob from the object URL const formData = new FormData(); formData.append('image', blob); // Submit the form via AJAX or another mechanism fetch('/upload', { method: 'POST', body: formData });</code>
The above is the detailed content of How to Convert an Object URL to a File or Blob for Form Submissions?. For more information, please follow other related articles on the PHP Chinese website!