【发布时间】:2021-03-19 14:58:39
【问题描述】:
我在开发工作中遇到了一些障碍。我正在尝试上传一张我在获取中使用 FormData 发送的照片。我猜我的问题出在我的内容标题或后端处理中。不管怎样,我似乎找不到解决办法。希望大家帮帮我
general.js - 这是我的请求处理程序
export const postDataWithImage = (url, data) => {
return fetch(url, {
body: data, // must match 'Content-Type' header
credentials: 'same-origin', //pass cookies, for authentication
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
})
.then(response => response.json()); // parses response to JSON
};
user-creation.js - 我对上面函数的实际使用(发送多个数据)
这是我正在发送的数据的图像 ![1] https://imgur.com/leBlC7L
const data = {...this.state, ...form};
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => formData.append(key, value));
postDataWithImage('/users', data)
.then(data => {
if (data.error) {
console.log("theres an error");
this.setState({
error: data["error"]
});
console.log(this.state.error);
} else {
console.log(data["data"]);
}
})
.catch(error => message.warning(error.message));
views.py - 我的后端处理程序不使用 Django REST:这会返回一个错误,要么字节没有属性 'get'... 要么是一个空的 ModelDict for request.FILES
@staticmethod
def post(request):
print(request.body.get('image'))
print(request.FILES)
if "username" not in request.data or "password" not in request.data:
return Response(data={
"error": "Missing username or password"
}, status=400, content_type="application/json")
return Response(data=data, status=200, content_type="application/json")
请帮帮我,我真的卡住了。谢谢!
【问题讨论】:
-
您是否成功向后端发送请求,例如邮递员?
-
是的,我将请求发送到后端。主要问题是后端无法正确读取文件/数据。
-
好的。您能否在将
this.state和form放入data之前将其包含在内? -
表格好了,当console.logged是这个imgur.com/leBlC7L
-
另外,如果我对 FormData 进行字符串化(我认为这会破坏图像格式),我需要的所有信息都可以通过调用 request.data 来检索
标签: javascript reactjs django-rest-framework fetch