Home > Web Front-end > JS Tutorial > How to Correctly Set FileList and File Properties When Using FormData?

How to Correctly Set FileList and File Properties When Using FormData?

Patricia Arquette
Release: 2024-12-08 06:19:10
Original
359 people have browsed it

How to Correctly Set FileList and File Properties When Using FormData?

How to set File objects and length property at FileList object where the files are also reflected at FormData object?

As described in the prompt, it's possible to set the .files property of the element to a FileList from another element's .files property or DataTransfer.files property.

However, the FileList object has a .length property that remains at 0 even after setting it through the .files property. Additionally, passing a

containing an with modified .files using this approach will result in a File object with a .size of 0.

To address this issue, it is necessary to first ensure that the FileList is mutable. This can be achieved by utilizing the DataTransfer constructor, creating a mutable FileList accessible through the DataTransferItemList.

Once the FileList is mutable, the files can be set individually using the DataTransferItemList.add() method. This will also ensure that the FileList.length property is set to the correct number of files.

By following this procedure, the files will also be reflected in the FormData object created from the form.

Here's an example:

const dT = new DataTransfer();
dT.items.add(new File(['foo'], 'programmatically_created.txt'));
document.querySelector('input[type="file"]').files = dT.files;
Copy after login

With this approach, the FileList of the element will be populated with the file created in the DataTransfer object. The FileList.length property will be set to 1, and the file will be reflected in the FormData object constructed from the form.

The above is the detailed content of How to Correctly Set FileList and File Properties When Using 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