我在开发工作中遇到了一些问题。我正在尝试使用fetch和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,但是这会返回一个错误,要么是byte没有'get'属性... 要么是request.FILES为空的ModelDict。
@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
是什么样子的? - Tholle