【问题标题】:How do I send a file to the Django server via ajax?如何通过 ajax 将文件发送到 Django 服务器?
【发布时间】: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


【解决方案1】:

如果您需要 utf-8,我认为您将“contentType”更改为“application/json”或“'application/json;charset=utf-8”。数据类型:'json'

dataType: 'json',
contentType: 'application/json; charset=utf-8',

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 2014-09-09
    • 2011-09-10
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多