【发布时间】:2021-10-13 18:47:41
【问题描述】:
我一个多星期都想不通,我需要向 Django 服务器发送图像,但我收到错误:415 (Unsupported Media Type)
如果我将 ContentType 更改为 multipart/form-data,我会得到: 400(错误请求)
通常是通过邮递员发送的,可能是什么错误?: (
脚本
updateUser() {
$.ajax({
url:
"http://localhost:8002/api/update_profile/" +
this.username +
"/",
data: {
first_name: this.first_name,
username: this.login,
last_name: this.last_name,
email: this.email,
photo: this.image
},
DataServiceVersion: 2.0,
processData: false,
contentType: false,
// contentType:"multipart/form-data",
type: "PUT",
success: function(data) {
location.reload()
},
error: function(response) {
console.log(this.data)
let err = response.responseJSON;
for (let key in err) {
alert(key, err[key].toString());
}
}
});
},
UPD。它对表单数据都不起作用
updateUser() {
const data = {
username: this.login,
first_name: this.first_name,
last_name: this.last_name,
email: this.email,
photo: this.image
}
let formData = new FormData()
Object.keys(data).forEach((key) => {
formData.append(key, data[key])
})
$.ajax({
url:
"http://localhost:8002/api/update_profile/" +
this.username +
"/",
data: {
formData
},
DataServiceVersion: 2.0,
processData: false,
//contentType: false,
contentType:"multipart/form-data",
type: "PUT",
success: function(data) {
loaction.reload()
},
error: function(response) {
console.log(this.data)
let err = response.responseJSON;
for (let key in err) {
alert(key, err[key].toString());
}
}
});
},
【问题讨论】:
-
form postman 你怎么发送数据是原始数据还是表单数据?
-
@Sumithran,我正在发送表单数据
-
您能分享一下您的看法吗?仅共享 javascript 代码不足以找出问题所在,但如果您使用 Django Rest Framework 和基于类的视图,您可能会错过视图上的
parser_classes属性。 -
@arif,是的,确实,在 Django 端加载图像存在问题。谢谢,我想错了方向!
标签: jquery django ajax django-rest-framework