Javascript/jQuery 附加到 FormData() 返回“未定义”

2023-12-28

我正在尝试使用 jQuery 进行简单的文件上传。我的 HTML 中有一个文件输入,如下所示:

<form id="PhotoUploadForm" action="/some/correct/url" method="post" enctype="multipart/form-data">
            <input type="file" id="uploadPhoto" accept="image">
</form>

我还有一些 JavaScript / jQuery 绑定到输入的更改事件,如下所示:

   $('#uploadPhoto').on("change", function (event) {

        var fileData = this.files[0];
        var data = new FormData();
        data.append('image',fileData);
        data.append('content','What could go wrong');
        console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

        $.ajax ({
            url: "/some/correct/url",
            type: 'POST',
            data: data,
            processData: false,
            beforeSend: function() {
               console.log('about to send');
            },
            success: function ( response ) {                   
                console.log( 'now do something!' )
            },
            error: function ( response ) {
                console.log("response failed");
            }
        });
    });

我注意到我收到了 500 错误!数据很可能不正确,我知道 URL 是正确的。所以我尝试将数据输出到控制台,我注意到我的数据附加了 return 'undefined'

console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

当我 console.log(data) 时,我得到以下信息:

FormData {append: function}__proto__: FormData

我在这里做错了什么吗?为什么是data.image & data.content不明确的?当我输出this.files[0]我得到以下信息:

File {webkitRelativePath: "", lastModified: 1412680079000, lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST), name: "2575-Web.jpg", type: "image/jpeg"…}lastModified: 1412680079000lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST)name: "2575-Web.jpg"size: 138178type: "image/jpeg"webkitRelativePath: ""__proto__: File

所以问题不在于图像。我对么?


Issue

你误解了FormData目的。 AFormData对象只有一个.append()方法,其中不向其附加属性,但仅存储提供的数据。因此,显然,.image and .content属性将是未定义的。

如果你想创建一个对象.image and .content属性,您应该创建一个常规对象,然后发送它。

解决方法

为了实现你想要的,你有一些选择:

  1. Using FormData:
    • 调用其构造函数传递<form>element 作为参数,它将为您完成所有工作。
    • 或者:创建对象然后使用.append() method.
  2. 使用常规对象并发送它。
  3. 使用常规对象,将其转换为 JSON 并使用contentType: 'application/json'.

你会选择什么选项?它只是取决于后端。如果您正在开发后端,请确保您正在从后端检索数据POST以正确的方式请求,否则请检查站点并查看您需要发送哪种数据。

Option 1

创建FormData object:

  • 方法一,让构造函数为你工作:

    var form = document.getElementById("PhotoUploadForm"),
        myData = new FormData(form);
    
  • 方法二,自己动手:

    var fileData = this.files[0],
        myData = new FormData();
    
    myData.append('image', fileData);
    

然后,稍后在您的代码中,您可以发送它:

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 2

创建一个常规对象并发送它:

var myData = {
        image: this.files[0]
    };

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 3

var myData = {
        image: this.files[0]
    };

myData = JSON.stringify(myData); // convert to JSON

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    contentType: 'application/json',
    data: myData, // here it is
    ...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript/jQuery 附加到 FormData() 返回“未定义” 的相关文章