Django:通过POST请求上传文件

时间:2018-07-05 11:43:09

标签: python django file post uploading

我正在尝试通过APIView上传文件,但是却遇到了异常:coord_cartesian(xlim = c(-10, 10)) 这是我的代码:

API视图:

{"exception": "ValidationException", "code": 401, "message": "You cannot access body after reading from request's data stream"}

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) 中没有其他中间件,我尝试禁用默认中间件,没有结果。

1 个答案:

答案 0 :(得分:0)

您必须在/ 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)