[英]django check if the uploaded file is a zip file
I have a handler for a POST method in Django which receives an uploaded file. 我在Django中有一个POST方法的处理程序,该处理程序接收上传的文件。 What I would like to do is verify that the file is a valid zip file before proceeding. 我想做的是在继续操作之前验证文件是否为有效的zip文件。
So, I have: 所以我有:
@login_required(login_url="login/")
def upload(request):
if request.method == 'POST' and request.FILES['upload_file']:
uploaded_file = request.FILES['upload_file']
print type(uploaded_file)
return render(request, 'upload.html', {'context': RequestContext(request)})
Now at this point uploaded_file
is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
. 现在,此时uploaded_file
的类型为<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
。 My question is what would be the best way to verify that this is a valid archive? 我的问题是验证这是一个有效档案的最佳方法是什么? Do I need to save it to the disk and then use the zipfile
module or is there some way to do it without writing to the disk? 我需要zipfile
其保存到磁盘上,然后使用zipfile
模块,还是可以通过某种方式在不写入磁盘的情况下进行操作?
Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons. 注意:出于各种不相关的原因,我没有将Django模型与FileField和相应的Form一起使用。
Yes, you should use zipfile
module. 是的,您应该使用zipfile
模块。
zipfile.is_zipfile(filename)
Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. 如果filename是基于其幻数的有效ZIP文件,则返回True;否则返回False。 filename may be a file or file-like object too. filename也可以是文件或类似文件的对象。 (Changed in version 3.1: Support for file and file-like objects.) (在版本3.1中更改:支持文件和类似文件的对象。)
Another option: (not likely but your choice) 另一种选择:(不太可能,但您可以选择)
How to detect type of compression used on the file? 如何检测文件上使用的压缩类型? (if no file extension is specified) (如果未指定文件扩展名)
You can find the header formats in the descriptions: 您可以在说明中找到标题格式:
Zip (.zip) format description, starts with 0x50, 0x4b, 0x03, 0x04 (unless empty — then the last two are 0x05, 0x06 or 0x06, 0x06) 邮政编码(.zip)格式说明,以0x50、0x4b,0x03、0x04开头(除非为空,否则最后两个为0x05、0x06或0x06、0x06)
Save the filename of the pbject 保存pbject的文件名
Name = request.FILES['filename'].name
Then check if is a zip file 然后检查是否为zip文件
If Name.endswith('.zip'):
print(True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.