L
L
life-f2021-10-01 14:54:35
AJAX
life-f, 2021-10-01 14:54:35

How to fetch image from ajax in django server and save?

Hello

When developing a project, I encountered a problem with saving profile images.
The front end is written in Vue.js with the Vuetify plugin. The image is added to v-input-file (essentially input[type=file]). Then, via ajax request, the image is passed to the django backend.
How to extract an object from a request and save it with django to the required folder on the server?

vue.js html

<v-file-input v-model="photoField" placeholder="Фото профиля" accept="image/*"
                          prepend-icon="" outlined></v-file-input>


AJAX
let fd = new FormData();
      let avatar = this.photoField;
      if (avatar !== undefined) {
        fd.append('image', avatar)
      } else {
        console.log("ERROR")
        return
      }

      $.ajax({
        url: this.$hostname + "profiles/" + this.currentProfile.id,
        type: "PUT",
        processData: false,
        data: fd,
        success: () => {
          console.log("Профиль изменен")
          this.loadData()
          this.photoDialog = false
        },
        error: (response) => {
          this.alertError = true
          this.alertMsg = "Непредвиденная ошибка"
          console.log(response.data)
        },
      })


When viewing the received data on the server, I get:
{"data":{"data":""------WebKitFormBoundaryghDtcs0s8LQanodr\r\nContent-Disposition: form-data; name":"\"image\"; filename=\"user1.png\"\r\nContent-Type: image/png\r\n\r\nPNG\r\n\u001a\n\u0000\u0000\u0000\r...","id":7}}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
life-f, 2021-10-15
@life-f

The answer was to use the axios library instead of jQuery.ajax. Through the data forms, the data was transferred to the server, where it was saved in the required format

const axios = require('axios')
      // чтение файла в formData
      let fd = new FormData();
      let avatar = this.photoField;
      if (avatar !== undefined) {
        fd.append('image', avatar)
      } else {
        console.log("ERROR")
        return
      }
      axios({
        method: 'put',
        url: this.$hostname + "time-tracking/profiles/" + this.currentProfile.id,
        headers: {"Authorization": "Token " + (sessionStorage.getItem("auth_token") || localStorage.getItem("auth_token"))},
        data: fd
      })
          .then(response => {
            console.log(response.data.data)
            this.loadData()
          });

E
Evgeny Akulinin, 2021-10-11
@forkhammer

You can get the file like this image_tmp_file is an object of type TemporaryUploadedFile, in fact a temporary file. You can save it directly to an ImageField or do other things.
image_tmp_file = request.FILES['image']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question