【问题标题】:How to Upload Images using React, fetch, and Django REST如何使用 React、fetch 和 Django REST 上传图像
【发布时间】: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.stateform 放入 data 之前将其包含在内?
  • 表格好了,当console.logged是这个imgur.com/leBlC7L
  • 另外,如果我对 FormData 进行字符串化(我认为这会破坏图像格式),我需要的所有信息都可以通过调用 request.data 来检索

标签: javascript reactjs django-rest-framework fetch


【解决方案1】:

我在使用 Vue.js 和 Django 时遇到了类似的问题。 最后我注意到问题是:boundary 没有设置到标题。

解决方案是从您的请求中删除 headers,如下所示:

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

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

【讨论】:

    【解决方案2】:

    尝试从 fetch 的标头中删除“Content-Type”

    【讨论】:

      【解决方案3】:

      我可以在fetch 请求的Content-Type 标头中看到一个问题。由于您正在传递其中包含图像的 FormData,因此必须将标头更新为:

       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: {
                      'Content-Type': 'multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD'
                  },
              })
                  .then(response => response.json()); // parses response to JSON
          };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 2018-04-27
        • 2021-08-20
        • 2017-10-23
        • 1970-01-01
        • 2021-03-25
        • 2019-08-21
        相关资源
        最近更新 更多