Home > Web Front-end > JS Tutorial > How to Programmatically Modify FileList and FormData for File Uploads?

How to Programmatically Modify FileList and FormData for File Uploads?

Susan Sarandon
Release: 2024-12-03 19:40:10
Original
763 people have browsed it

How to Programmatically Modify FileList and FormData for File Uploads?

How to Modify FileList and FormData with Specified Files

Setting the .files property of an element with a FileList from another or DataTransfer.files allows you to specify the files to be uploaded. However, this approach presents challenges:

  • The .files.length property remains at 0.
  • The File object passed to FormData() has a .size of 0.

Solution Using DataTransfer

The DataTransfer constructor creates a mutable FileList accessible through the DataTransferItemList. To set arbitrary files on a FileList, you can use the following approach:

const dT = new DataTransfer();
dT.items.add(new File(['foo'], 'programmatically_created.txt'));
inp.files = dT.files;
Copy after login

Here, dT is a new DataTransfer object, and inp is your input element. This technique allows you to set specific files, update the FileList's .length property, and ensure that the files are reflected in the FormData object.

The above is the detailed content of How to Programmatically Modify FileList and FormData for File Uploads?. 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