Javascript/jQuery追加到FormData()返回'undefined'

Mar*_*man 7 html javascript jquery

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

<form id="PhotoUploadForm" action="/some/correct/url" method="post" enctype="multipart/form-data">
            <input type="file" id="uploadPhoto" accept="image">
</form>
Run Code Online (Sandbox Code Playgroud)

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

   $('#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");
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

我注意到我得到了500错误!很可能数据不正确,我知道网址很好.所以我试着将数据输出到控制台,我注意到我的数据追加了' undefined'

console.log(data.image, data.content); // this outputs 'undefined undefined' in the console
Run Code Online (Sandbox Code Playgroud)

当我console.log(数据)时,我得到以下内容:

FormData {append: function}__proto__: FormData
Run Code Online (Sandbox Code Playgroud)

我在这里做错了吗?为什么data.imagedata.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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*lli 13

问题

你误解了这个FormData对象.甲FormData对象只有一个.append()方法,该方法不追加属性它,但只存储所提供的数据.因此,显然,.image.content属性将是不确定的.

如果要创建具有.image.content属性的对象,则应创建常规对象,然后发送它.

解决方法

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

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

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

选项1

创建FormData对象:

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

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

选项2

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

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

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

选项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
    ...
});
Run Code Online (Sandbox Code Playgroud)