Django Rest Framework: Upload file via AJAX

后端 未结 1 931
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 15:43

I have a view and serializer:

class UserView(generics.RetrieveUpdateAPIView):
    model = get_user_model()
    serializer_class = UserProfileSerializer
    p         


        
相关标签:
1条回答
  • 2021-01-20 16:42

    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>
    
    0 讨论(0)
提交回复
热议问题