【问题标题】:DJango Python File Upload how to preserve orginal fileDJango Python File Upload如何保存原始文件
【发布时间】:2017-09-27 17:24:49
【问题描述】:

我正在尝试使用 Rest 将文件上传到 DJango Python API。但我注意到文件被修改了。具体来说,会向其中添加内容处置。我还没有找到删除它的好方法。问题是我正在尝试上传需要解压缩的 tar,但修改后的内容会阻止解压缩文件。

我在休息页面上使用这个文件解析器: 从 rest_framework.parsers 导入 FileUploadParser

以下代码似乎在 APIView 的 post 方法中为我获取文件

file_obj = request.FILES['file']
scanfile.file.save(file_obj.name, file_obj)

其中 scanfile 是具有文件字段的模型。 该文件将保存如下内容:

--b3c91a6c13e34fd5a1e253b1a72d63b3
Content-Disposition: form-data; name="file"; filename="sometar.tgz"
My tar file contents here.....
--b3c91a6c13e34fd5a1e253b1a72d63b3

我的客户是这样的:

filename = "sometar.tgz"
exclusion = "../../exclusionlist.txt"
headers = {'Content-Type': 'multipart/form-data;’,
           'Authorization': 'JWT %s' % token,
           }
url = "http://localhost:%s/api/scan/Project/%s/" % (port, filename)
#files = {'file': open(filename, 'rb'), 'exclusion_file': open(exclusion, 'rb')}  # also tried this way but it just put the info in the same file and I see the headers in the file
files = [('file', open(filename, 'rb')), ('file', open(exclusion, 'rb'))]
x = requests.post(url, files=files, headers=headers)

所以我的问题是如何从保存的文件中删除内容处置信息,以便正确解压缩文件?

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    request.FILES['file'] 是一个 UploadedFile 对象。您可以使用request.FILES['file'].name 获取其名称,并使用request.FILES['file'].read() 获取其内容。

    您应该小心read() 和大文件:

    从文件中读取整个上传的数据。小心这个 方法:如果上传的文件很大,如果 您尝试将其读入内存。你可能想要使用 chunks() 反而;见下文。

    https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.FILES https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile

    【讨论】:

    • 我也尝试过 .read() 和 .chunks() ,无论哪种方式,文件中仍然有 content-disposition 标签。
    • 我有一个解决方法,但它涉及手动删除行:使用 tempfile.NamedTemporaryFile() 作为 tmp:lines = file_obj.readlines() tmp.writelines(lines[3:-1]) tmp。寻找(0)
    • 我再次尝试 read() 并得到一个错误。所以这就是我没有使用它的原因。文件“/utils.py”,第 16 行,在 read = property(lambda self: self.file.read) AttributeError: 'str' object has no attribute 'read' code 现在是 scanfile.file.save(file_obj .name, file_obj.read()) 但它似乎是一个字符串而不是 UploadedFile。 scanfile 仍然是 file_obj = request.FILES['file']
    • 尽量不要明确设置Content-Type 并让请求为您处理它。还要尝试两个不同的文件名,否则 Django 可能只显示一个。除此之外,请尝试使用 Wireshark 或其他调试工具来验证请求是否符合您的预期。
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2014-06-14
    • 2016-02-04
    • 2021-05-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多