Django Rest Framework: Upload file via AJAX

Tom Carrick

I have a view and serializer:

class UserView(generics.RetrieveUpdateAPIView):
    model = get_user_model()
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_object(self, *args, **kwargs):
        return self.request.user


class UserImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('image',)

They work great with httpie:

http -f put localhost:8000/accounts/api/image/ "Authorization: Token mytoken" image@~/Downloads/test.jpg
HTTP/1.0 200 OK
Allow: GET, PUT, PATCH, HEAD, OPTIONS
Content-Type: application/json
Date: Thu, 03 Sep 2015 22:50:33 GMT
Server: WSGIServer/0.2 CPython/3.4.3
Vary: Accept
X-Frame-Options: SAMEORIGIN

{
    "image": "http://localhost:8000/media/accounts/user_images/test.jpg"
}

and my image is uploaded and shows up in the admin.

Now I want to be able to upload a file using AJAX, but it apparently doesn't want to work:

<form action="http://localhost:8000/accounts/api/image/"
      method="put"
      enctype="multipart/form-data">
    <input name="image" type="file">
    <input type="submit">
</form>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<script>
    $('form').submit(function(e) {
        var formData = new FormData($(this));
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: formData,
            headers: {'Authorization': 'Token mytoken'},
            cache: false,
            contentType: false,
            processData: false,
            success: function() { alert('it works') },
        });
        e.preventDefault();
    });
</script>

Now, my "It works" alert appears. I know the form is being submitted to the right place, I can see in the Django dev server that it's being requested as PUT and that it responds with 200 (same response as with httpie):

[03/Sep/2015 22:47:23] "PUT /accounts/api/image/ HTTP/1.1" 200 77

But it seems like the file isn't being uploaded, and it doesn't show up in the admin.

I'm out of ideas.

Tom Carrick

Ok, I can't exactly explain why, but it seems like var formData = new FormData($(this)); is not enough alone, it needs to be explicitly appended, because reasons? If anyone can explain, please do.

The working code:

<form action="http://localhost:8000/accounts/api/image/"
      method="put"
      enctype="multipart/form-data">
    <input name="image" type="file" id="image">
    <input type="submit">
</form>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<script>
    $('form').submit(function(e) {
        var formData = new FormData($(this));
        formData.append('image', $('#image')[0].files[0]);
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: formData,
            headers: {'Authorization': 'Token mytoken'},
            cache: false,
            contentType: false,
            processData: false,
            success: function() { alert('it works') },
        });
        e.preventDefault();
    });
</script>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Django Rest Framework File Upload

From Dev

Django REST Framework file upload

From Java

Large file upload to Django Rest Framework

From Dev

Django REST Framework and File Upload (Data URI)

From Dev

Django Rest Framework upload file to a method

From Dev

Django REST Framework and File Upload (Data URI)

From Dev

How do I upload an image via Django Rest Framework?

From Dev

How to upload file via an AJAX form in Zend Framework 2?

From Dev

Django REST Framework upload image: "The submitted data was not a file"

From Dev

Upload file via rest service

From Dev

Submit file upload via Ajax

From Dev

Django JQuery Ajax File Upload

From Dev

Django Rest Framework image upload and get image

From Dev

How to upload multiple files in django rest framework

From Dev

Django Rest Framework : Upload Image API

From Dev

Unable to upload file via REST request in GRAILS

From Dev

django rest framework return file

From Dev

Django Rest framework replacing my currently authenticated user with AnonymousUser whenever I call it via ajax?

From Dev

Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX

From Dev

Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX

From Dev

Django REST Framework file upload causing an "Unsupported media type 'multipart/form-data'" error

From Dev

Laravel5 file Upload via Ajax

From Dev

Upload file Vue 3 and Django REST

From Dev

Django: Upload file via POST request

From Dev

Multiple file upload via ajax, uploading file multiple times

From Dev

Uploading a file with Django REST framework ListCreateAPIView

From Dev

Uploading a file with Django REST framework ListCreateAPIView

From Dev

Display Static file Django and rest-framework

From Dev

Is there a way to upload files using the browsable API in Django REST framework?

Related Related

  1. 1

    Django Rest Framework File Upload

  2. 2

    Django REST Framework file upload

  3. 3

    Large file upload to Django Rest Framework

  4. 4

    Django REST Framework and File Upload (Data URI)

  5. 5

    Django Rest Framework upload file to a method

  6. 6

    Django REST Framework and File Upload (Data URI)

  7. 7

    How do I upload an image via Django Rest Framework?

  8. 8

    How to upload file via an AJAX form in Zend Framework 2?

  9. 9

    Django REST Framework upload image: "The submitted data was not a file"

  10. 10

    Upload file via rest service

  11. 11

    Submit file upload via Ajax

  12. 12

    Django JQuery Ajax File Upload

  13. 13

    Django Rest Framework image upload and get image

  14. 14

    How to upload multiple files in django rest framework

  15. 15

    Django Rest Framework : Upload Image API

  16. 16

    Unable to upload file via REST request in GRAILS

  17. 17

    django rest framework return file

  18. 18

    Django Rest framework replacing my currently authenticated user with AnonymousUser whenever I call it via ajax?

  19. 19

    Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX

  20. 20

    Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX

  21. 21

    Django REST Framework file upload causing an "Unsupported media type 'multipart/form-data'" error

  22. 22

    Laravel5 file Upload via Ajax

  23. 23

    Upload file Vue 3 and Django REST

  24. 24

    Django: Upload file via POST request

  25. 25

    Multiple file upload via ajax, uploading file multiple times

  26. 26

    Uploading a file with Django REST framework ListCreateAPIView

  27. 27

    Uploading a file with Django REST framework ListCreateAPIView

  28. 28

    Display Static file Django and rest-framework

  29. 29

    Is there a way to upload files using the browsable API in Django REST framework?

HotTag

Archive