使用React、fetch和Django REST如何上传图片

3
我在开发工作中遇到了一些问题。我正在尝试使用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")

请帮助我,我真的被卡住了。谢谢!


你是否成功使用 Postman 发送了请求到你的后端? - Tholle
是的,我已经向后端发送了请求。主要问题是后端无法正确读取文件/数据。 - Jason
好的。在你把它放进"data"之前,你能否包含一下你的this.stateform是什么样子的? - Tholle
表单在控制台记录时是这样的 https://imgur.com/leBlC7L - Jason
此外,如果我对 FormData 进行字符串化处理(我认为这将破坏图片格式),则可以通过调用 request.data 检索到所需的所有信息。 - Jason
好的。这很令人沮丧。我不确定问题出在哪里,但看起来你的“image”文件已被转换为常规对象。如果您不将“File”附加到“FormData”,可能会丢失一些信息。 - Tholle
2个回答

0
我在使用Vue.js和Django时遇到了类似的问题。 最终我发现问题是这样的:boundary没有被设置到头部。

解决方案是从请求中删除headers,像这样:

fetch(url, {
            body: data,  // assume this is some binary data
            method: 'POST',
})

然后,您的浏览器将自动为您的请求添加适当的标头。您将看到boundary字段,该字段是由您的浏览器在请求标头中添加的。


-1
尝试从fetch的头部中删除“Content-Type”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接