简体   繁体   English

Django文件上传

[英]Django file uploading

I need to have the ability to upload files on the server but before uploading I would like to verify this file whether this file is and image or a script called image.jpeg. 我需要能够在服务器上传文件,但在上传之前我想验证这个文件是否是这个文件和图像或者是一个名为image.jpeg的脚本。 For this I'm using a library called python-magic 为此,我使用了一个名为python-magic的库

import magic

attachment = request.FILES['file'].read()
m = magic.open(magic.MAGIC_MIME_TYPE)
m.load()
ft = m.buffer(attachment)
m.close()

Its working fine for me. 它对我来说很好。 But should I read whole file? 但是我应该阅读整个文件吗?

 attachment = request.FILES['file'].read()

I think that this is a bad idea so my question is how much header of file weight? 我认为这是一个坏主意,所以我的问题是文件权重多少? So than i can read only couple bytes and verify files mime-type. 因此,我只能读取几个字节并验证文件mime-type。

You could first guess the mimetype using the mimetype module as suggested here . 您可以首先使用此处建议的mimetype模块猜测mimetype。 If you are ok with the guess, upload the file to your webserver. 如果您对猜测没问题,请将文件上传到您的网络服务器。 In the case that you will access the file afterwards, you can do the entire check with the source you provided, as you have to read the file anyway. 如果您之后将访问该文件,您可以使用您提供的源进行整个检查,因为您无论如何都必须阅读该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM