Javascript/jQuery Append to FormData()返回'未定义'

Javascript/jQuery Append to FormData() returns 'undefined'

本文关键字:返回 未定义 jQuery Append to FormData Javascript      更新时间:2023-09-26

我正在尝试使用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!最有可能的数据是不正确的,我知道网址是好的。因此,我尝试将数据输出到控制台,并注意到我的数据附加了返回"undefined"

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

当我控制台.log(数据)我得到以下:

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

所以问题不在于图像。我说得对吗?

问题

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

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

变通办法

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

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

您会选择什么选项它仅依赖于后端。如果您正在开发后端,请确保以正确的方式从POST请求中检索数据,否则请检查网站并查看需要发送的数据类型。

选项1

创建FormData对象:

  • 方法1,让构造函数为您工作:

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

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

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

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

选项2

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

var myData = {
        image: this.files[0]
    };
$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

选项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
    ...
});