Django:通过 POST 请求上传文件

Django: Upload file via POST request

我正在尝试通过 APIView 上传文件,但出现异常:{"exception": "ValidationException", "code": 401, "message": "You cannot access body after reading from request's data stream"} 这是我的代码:

API 查看:

class SetAvatarView(LoginRequiredAPIView):
    @csrf_exempt  # Does no affect to situation
    def post(self, request):
        try:
            request.account.update_avatar(request.FILES['file'])
        except ValidationException, e:
            return JsonResponse(e.to_dict(), status=400)
        return JsonResponse({}, 200)

Account 型号:

class Account(models.Model):
    ...
    avatar = models.ImageField(upload_to=AVATARS_URL, default='default.jpg')
    ...
    def update_avatar(self, f):
        self.avatar = f

上传文件测试代码:

def test_set_avatar(self):
    url = "/account/avatar/set/"
    with open("test.jpg", "r") as fp:
        response = self.client.post(url, {'file': fp}, #content_type='multipart/form-data', # Getting 400 Bad Request if uncomment
                                    **{'HTTP_AUTHORIZATION': 'Token 0ff0884090**********8ef5387423bc24cd15e1'})
    print response.content
    self.assertEqual(response.status_code, 200)

settings.py 中没有额外的中间件,我尝试禁用默认中间件,没有结果。

您必须在视图中对文件进行编码和解码/account/avatar/set

import base64 
def test_set_avatar(self):
    url = "/account/avatar/set/"
    with open("test.jpg", "r") as fp:
    response = self.client.post(url, {'file': base64.b64encode(fp.read())}, #content_type='multipart/form-data', # Getting 400 Bad Request if uncomment
                                **{'HTTP_AUTHORIZATION': 'Token 0ff0884090**********8ef5387423bc24cd15e1'})
    print response.content
    self.assertEqual(response.status_code, 200)