Django Rest Framework:通过 AJAX 上传文件

Django Rest Framework: Upload file via AJAX

我有一个视图和序列化程序:

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',)

它们与 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"
}

我的图片已上传并显示在管理员中。

现在我希望能够使用 AJAX 上传文件,但它显然不想工作:

<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>

现在,我的 "It works" 警报出现了。我知道表单被提交到正确的地方,我可以在 Django 开发服务器中看到它被请求为 PUT 并且它以 200 响应(与 httpie 相同的响应):

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

但是文件似乎没有被上传,也没有显示在管理中。

我没主意了。

好吧,我不能确切地解释为什么,但似乎 var formData = new FormData($(this)); 是不够的,它需要明确地追加,因为原因?如果有人可以解释,请做。

工作代码:

<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>