How do I send a file to the Django server via ajax?

Viewed 79

I can't figure out for more than a week, I need to send an image to the Django server, but I get the error: 415 (Unsupported Media Type)

If I change ContentType to multipart/form-data, I get: 400 (Bad Request)

is sent via postman normally, what could be the error?: (

Script

    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. it doesn't work either form data

    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());
          }
        }
      });
  },
1 Answers

i think you change "contentType" to "application/json" or "'application/json; charset=utf-8" if you need utf-8. dataType :'json'

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