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

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

我还有一些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"); } }); }); 

我注意到我得到了500错误! 很可能数据不正确,我知道url很好。 所以我尝试将数据输出到控制台,我注意到我的数据追加返回’ undefined

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

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

 FormData {append: function}__proto__: FormData 

我在这里做错了吗? 为什么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 

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

问题

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

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

解决方法

为了达到你想要的效果,你有一些选择:

  1. 使用FormData
    • 调用它的构造函数传递

      元素作为参数,它将为您完成所有工作。

    • 或者:创建对象,然后使用.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 ... });