【问题标题】:DRF file.read() contains HTML header info and not just file contentDRF file.read() 包含 HTML 标头信息,而不仅仅是文件内容
【发布时间】:2017-12-31 14:35:09
【问题描述】:

我不确定问题出在哪里,但 file.read() 应该只给我文件内容。我正在打印前 200 个字符并获取内容标题,而不仅仅是上传的文件数据。

上传者

local_file = os.path.join(basedir, 'a.jpg')
url = baseurl + 'a.jpg'
files = {'file': open(local_file, 'rb')}
headers = {'Authorization': 'Token sometoken'}
r = requests.put(url, files=files, headers=headers)
print(r.status_code)

查看

class FileUploadView(BaseAPIView):
    parser_classes = (FileUploadParser,)

    def put(self, request, filename):
        file_obj = request.FILES['file']
        data = file_obj.read()
        print(data[:200])
        return Response(status=HTTP_204_NO_CONTENT)

打印的输出是:

b'--139822073d614ac7935850dc6d9d06cd\r\n内容配置:表单数据;名称=“文件”;文件名="a.jpg"\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\ xe1!(Exif\x00\x00II*\x00\x08\x00\x00\x00\r\x00\x0b\x00\x02\x00\r\x00\x00\x00\xaa\x00\x00\x00\x00\ x01\t\x00\x01\x00\x00\x00x\x03\x00\x00\x01\x01\t\x00\x01\x00\x00\x00\xe8\x03\x00\x00\x0f\x01\x02\ x00\x04\x00\x00\x00HTC\x00\x10\x01\x02\x00\x0b\x00\x00\x00\xb8\x00\x00'

我怎么会看到所有这些额外的数据而不仅仅是文件内容? Dis 一直让我发疯,而且可能会很简单。

【问题讨论】:

  • 不太确定,但也许可以尝试切换到POST 或将内容类型明确设置为multipart/form-data
  • 谢谢@Cory。我得到了它的工作,但我要切换到多部分。似乎是更好的选择。

标签: django django-rest-framework python-requests


【解决方案1】:

使用 FileUploadParser 您需要发送带有数据的文件内容

with open(local_file, 'rb') as fh:
    r = requests.put(url, data=fh, headers=headers, verify=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2015-08-12
    相关资源
    最近更新 更多