我正在尝试使用 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
所以问题不在于图像。我对么?