Python压缩文件.ZipFile压缩损坏的文件



我有一个Django视图,用户可以调用它来压缩本地服务器上的文件。它使用zipfile.ZipFile将多个文件压缩为一个zip,如下所示:

with ZipFile(my_dir + 'folder.zip', 'w') as zipObj:
zipObj.write(my_dir + '1.json')
zipObj.write(my_dir + '2.json')

然后我将此文件返回给用户作为响应:

folder_file = open(full_path, "r", encoding='Cp437')
response = HttpResponse(FileWrapper(folder_file), content_type='application/zip')

但下载的文件已损坏,我无法使用ubuntu档案管理器打开它。

然后,当我尝试使用django服务器中的相同包使用python解压缩文件时,我仍然会收到错误:

with ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(my_dir)

我得到的错误是:

File ".../views.py", line 38, in post
with ZipFile(file_path, 'r') as zip_ref:
File "/usr/lib/python3.8/zipfile.py", line 1269, in __init__
self._RealGetContents()
File "/usr/lib/python3.8/zipfile.py", line 1354, in _RealGetContents
fp.seek(self.start_dir, 0)
OSError: [Errno 22] Invalid argument

你知道我在这里做错了什么吗?

这应该是一个注释,但我认为它太长了。

我认为你应该看看自己的道路,因为错误的道路会导致不必要的行为。从zip文件写入:

归档文件名应该相对于归档文件根,也就是说,它们不应该以路径分隔符开头。

和来自zipfile extratc(all(:

如果成员文件名是绝对路径,则驱动器/UNC共享点和前导(后(斜杠将被剥离,例如:///foo/bar在Unix上变成foo/bar,C:\foo\bar在Windows上变成foo\bar。而所有的"成员文件名中的组件将被删除,例如:../../foo../ba..r变成foo/ba…r在Windows上,非法字符(:、<、>、|、"、?和*(被下划线(_(替换。

所以请确保使用正确的路径。并确保它们没有像这里那样的问题字符(如通配符或反斜杠(

也许你应该用其他(非(zip tootl测试一下,看看它是否有区别,有时它们更具体(比如这里(

您可以尝试这样的方法。

zipf = ZipFile("whatever.zip", "w")
for file in files_to_add:
this_file = urlopen(file).read()
this_filename = 'file name.json'
zipf.writestr(this_filename, this_file)
zipf.close()
response = HttpResponse(io.open("whatever.zip", mode="rb").read(), content_type="application/zip")
response["Content-Disposition"] = "attachment; filename=whatever_name_you_want.zip"
return response

在创建HttpResponse时以二进制模式打开zip文件,以避免换行转换时出错:

folder_file = open(full_path, "rb")
response = HttpResponse(FileWrapper(folder_file), content_type='application/zip')

最新更新