K
K
ksksksks2019-04-21 22:36:34
Django
ksksksks, 2019-04-21 22:36:34

How to send file via ajax to server?

Hello, for more than a week I can't figure it out, I need to send an image to the Django server, but I get an error:
415 (Unsupported Media Type)
{"detail":"Unsupported data type \"text/plain;charset=UTF-8\" in request."}
If I change the ContentType to multipart/form-data, I get:
400 (Bad Request)
It is sent normally via postman, what could be the error? :(
Script:

$(function() {
  // при нажатии на кнопку "Отправить"
  $('#upload-image').click(function() {
    // элемент, с помощью которого пользователь выбирает файл
    var file = $('#file');

    var result = $('#result');
    // если файл выбран, то
    if (file.prop('files').length) {
      // создаём объект FormData
      var formData = new FormData();
      // добавляем в объект FormData файл
      formData.append('img', file.prop('files')[0]);

      $.ajax({
        url: "http://127.0.0.1:8000/api/v2/update-ava/11/",
        data: {
          pk: 11,
          img: formData,
        },
        DataServiceVersion: 2.0,
        processData: false,
        contentType: false,
        // contentType:"multipart/form-data",
        type: 'PUT',


        success: function(data) {
          result.html(data);
        }
      });
    } else {
      result.html("Не выбран файл для загрузки!");
    }
  });
});

On server:
class UpdateProfile(APIView):
    """Редактирование аватара"""
    permission_classes = [permissions.AllowAny]
    # parser_classes = (FileUploadParser,)
    # parser_classes = (MultiPartParser, FormParser)
    # parser_classes = (FileUploadParser,)
    def get_object(self, pk):
        try:
            return Profile.objects.get(pk=pk)
        except Profile.DoesNotExist:
            raise Http404

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = RedactIMG(instance=snippet, data=request.data, partial=True)
        if serializer.is_valid():
            if "img" in request.FILES:
                serializer.save(img=request.data["img"])
                serializer.save()
                return Response(serializer.data,status=201)
            return Response(serializer.errors,status=400)
        else:
            return Response(serializer.errors,status=400)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2019-04-22
@ksksksks

So you have here

data: {
          pk: 11,
          img: formData,
        },

img is not an image, it's FormData. It's more correct like this
var formData = new FormData();
      // добавляем в объект FormData файл
      formData.append('img', file.prop('files')[0]);
      formData.append('pk', 11);
      $.ajax({
        url: "http://127.0.0.1:8000/api/v2/update-ava/11/",
        data: formData,
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question