简体   繁体   English

FormData添加文件不起作用

[英]FormData add file doesn't work

I have form: 我有形式:

<form enctype="multipart/form-data" action="" method="post"  id="sendInvoiceForm">
    <input type="text" value="Some text">
    <input name="file[]" type="file"  multiple/>
    <input type="button" id="upload" value="Upload File" />
</form>

My js: 我的js:

$('#upload').click(function(e) {
            e.preventDefault();
            var formData = new FormData();
            formData.append('files',$("#sendInvoiceForm")[0]);
            $.ajax({
                url: 'upload.php',
                type: 'POST',
                xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    return myXhr;
                },
                success: function (data) {
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
        });

When I try to get my 'files' in php I get only [object HTMLFormElement] How can I get my files on php? 当我试图在php中获取我的'文件'时我只得到[对象HTMLFormElement]如何在php上获取我的文件?

But if I create my formData as : var formData = new FormData($("#sendInvoiceForm")[0]); 但是如果我将formData创建为: var formData = new FormData($("#sendInvoiceForm")[0]); I can find my files in _FILES, but I need give name for this array. 我可以在_FILES中找到我的文件,但我需要为这个数组命名。

How can I solve this problem? 我怎么解决这个问题? Thanks 谢谢

The issue is because you're appending the form DOM Element to the FormData, not the file data. 问题是因为您将form DOM元素附加到FormData,而不是文件数据。 Instead, you should access the files array of that object: 相反,您应该访问该对象的files数组:

formData.append('files', $('#sendInvoiceForm input[type="file"]')[0].files[0]);

As there can be multiple files selected, you'll need to loop through them: 由于可以选择多个文件,因此您需要循环遍历它们:

$('#sendInvoiceForm input[type="file"]')[0].files.forEach(function(file) {
  formData.append('files', file, file.name);
});

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

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