0

im trying to compress uploaded files in django using 7zip.

i have successfully implemented compression and decompression of files using 7zip in python but i am not able to figure out how to integrate the same with django uploaded file so that whenever a file is uploaded ,a 7zp format for the same file is create and stored in the disk.

Code used in python for compression :

import subprocess
from py7zr import unpack_7zarchive
import shutil

exe = r"C:\Program Files\7-Zip\7zG.exe"
source = r"C:\profiles\Living in the Light_ A guide to personal transformation.pdf"
target = r"C:\profiles\Living1.7z"

def compress(source,traget):
    subprocess.call(exe + " a -t7z \"" + target + "\" \"" + source + "\" -mx=9")
    print('file compressed')

def uncompress(target):
    shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)
    shutil.unpack_archive(target, r'C:\Users\098an\Pictures\Camera Roll')
    print('file uncompressed')
anu
  • 15
  • 7

1 Answers1

1

I believe there are Django-specific tools that you must use other than 7-zip. One problem using 7-zip on the web is that, if the client's computer doesn't have it installed, your server won't run correctly.

I know two ways to work this out: if you are simply looking to compress images, you can refer to this dev.to article on compressing images specifically. The other way to work this out is requiring users to upload in the form of zip files as described here, but change the file extensions to .zip, .rar, or whatever you deem necessary

EDIT

There are ways to automatically zip all types of files such as this pypi package, but I'm not sure how those will work out as it's not a mainstream package. If you want to conserve upload space, try setting a size bound instead.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27
  • i have to compress filefields such that user can upload any file format i.e. pdf,docx etc and its is automatically stored in disk as filename.zip. – anu Jul 14 '20 at 10:43
  • i tried using pypi package but it alwasy give import error : from compress_field import ZipFileFieldImportError: cannot import name 'ZipFileField' from 'compress_field. Other than this, i want to compress the file to reduce the memory used.i dont want to put any limitation to the size of the file uploaded. – anu Jul 14 '20 at 11:10
  • "I'm not sure how those will work out as it's not a mainstream package" that's where the problem starts. There aren't many people doing zip files since most of them just limit the upload size of a document. Plus you might need to decompress it which takes even more time. – crimsonpython24 Jul 14 '20 at 11:11