简体   繁体   English

如何将数组中的单个文件附加到FormData?

[英]How to append a single file in an Array to FormData?

I have a list of files that need to be uploaded to an AJAX call. 我有一个需要上传到AJAX调用的文件列表。 I use formData.append('uploads[]', fileList[i], names[i]) to do it. 我使用formData.append('uploads[]', fileList[i], names[i])来做到这一点。

If the fileList contains multiple files, the uploads[] received by server will be an array of files. 如果fileList包含多个文件,则服务器收到的uploads[]将是文件数组。 This works perfect fine. 这非常完美。

The problem is : If the fileList contains only one file, the server will get the file rather than an array of one file, which causes issue. 问题是:如果fileList仅包含一个文件,则服务器将获取该文件,而不是一个文件的数组,这将导致问题。

Any idea how can I put the file to an array when there is only one file? 知道只有一个文件时如何将文件放入数组吗?

Just generate an array by wrapping your file into brackets... 只需将文件包装在方括号中即可生成数组...

formData.append('uploads[]', [fileList[i]], names[i])

or to be more precise, names should also be an array I guess: 更确切地说,我猜名字也应该是一个数组:

formData.append('uploads[]', [fileList[i]], [names[i]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM