2

I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding.

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'>. 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?

Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons.

Luca
  • 10,458
  • 24
  • 107
  • 234

2 Answers2

7

Yes, you should use zipfile module.

zipfile.is_zipfile(filename)

Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too. (Changed in version 3.1: Support for file and file-like objects.)

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)

Community
  • 1
  • 1
nivhanin
  • 1,688
  • 3
  • 19
  • 31
  • 1
    yeah, the thing is that the file will have to be stored to be able to use with `zipfile`. I guess there is no other really good way to do this. – Luca Mar 30 '17 at 14:42
0

Save the filename of the pbject

Name = request.FILES['filename'].name

Then check if is a zip file

If Name.endswith('.zip'):
     print(True)
Mattia
  • 961
  • 13
  • 25
  • It has the same issue as I mentioned before of having to store the file. I guess there is no really good and robust way to check an in-memory file. – Luca Mar 30 '17 at 21:42