【发布时间】:2017-10-12 20:26:38
【问题描述】:
我正在尝试将图像上传到我的后端。我需要连同这张图片一起发送三样东西——文件(一个网址)和标题。我已经尝试过这样做,但收到错误消息说 400 bad request。在网络选项卡中,我看到这样的响应
这是我的代码
posterFile = e.target.files;
selectedPoster = posterFile[0];
uploadPoster() {
var blobPosterFile = selectedPoster;
console.log("U called me?")
var formData = new FormData();
formData.append("fileToUpload", blobPosterFile);
var that = this;
let token;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.backend.sample.forexom.com/api/v1/videos/",
"method": "POST",
processData: false,
"credentials": 'include',
"headers": {
Authorization: "Token " + that.props.token_Reducer.token
},
"data": {
"file": JSON.stringify(videoURL),
"poster": formData,
"title": JSON.stringify(selectedFile.name)
},
success:( response, textStatus, jQxhr )=> {
//this.props.tokenAction(response.auth_token);
console.log("poster uploaded")
}
}
$.ajax(settings).done((response) => {
});
}
更新
尝试像这样将其他数据附加到 formData,但得到同样的错误
uploadPoster() {
var blobPosterFile = selectedPoster;
console.log("U called me?")
var formData = new FormData();
formData.append("file", videoURL)
formData.append("poster", blobPosterFile);
formData.append("title", selectedFile.name)
var that = this;
let token;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.backend.trigger.tessact.com/api/v1/videos/",
"method": "POST",
processData: false,
"credentials": 'include',
"headers": {
"content-type": "application/x-www-form-urlencoded",
Authorization: "Token " + that.props.token_Reducer.token
},
"data": formData,
success:( response, textStatus, jQxhr )=> {
//this.props.tokenAction(response.auth_token);
console.log("poster uploaded")
}
}
$.ajax(settings).done((response) => {
});
}
【问题讨论】:
-
400 错误意味着服务器无法理解请求。问题出在服务器端,服务器所期望的和接收到的,并没有计算出来。原因是您只能将 formData 作为 only 数据发送到服务器,如果要添加更多信息,则必须将其附加到要发送的 formData 对象中。
-
您似乎没有为数据变量提供任何值(即
videoURL、formData、selectedFile.name),请仔细检查它们。如果该值存在,那么您的后端可能有问题。 -
@adeneo 但是后端需要三个字段。我怎样才能通过附加来做到这一点?
-
@Gerry 他们有价值观。
-
@ApurvG - 您已经在代码中附加到 formData,将其他值附加为键/值对是相同的,然后只需执行
data : formData。您可以仅发送 formData,当您禁用processData时,您不能将对象用作 jQuery 的$.ajax的数据,因为该对象不会转换为 x-www-urlencoded等等
标签: javascript jquery ajax form-data