Login

Unzip a .zip file uploaded with FileBrowser

Author:
shacker
Posted:
January 27, 2010
Language:
Python
Version:
1.1
Tags:
filebrowser zip unzip
Score:
2 (after 2 ratings)

Django Filebrowser (http://code.google.com/p/django-filebrowser/) provides a signal called filebrowser_post_upload. Adding this method to a model that has a FileBrowse field will cause uploaded .zip files to be detected and unzipped on the server in place, then deleted (leaving their folder behind). It will also delete the garbage __MACOSX folder created by Mac zip files.

This is probably not safe to do for publicly uploaded files. The use case here was to allow journalists to upload entire SoundSlides projects into a custom CMS.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from filebrowser.fields import FileBrowseField
from filebrowser.views import filebrowser_post_upload
import sys, zipfile, os, os.path
import shutil
        
class Media(models.Model):
    #...
    file = FileBrowseField("File", max_length=200, directory="shells/",  blank=True, 
        null=True,help_text="Upload a video/image/swf, zipped slideshow, etc.")
    #...
    
        
    def post_upload_callback(sender, **kwargs):
        """
        Signal receiver called each time an upload has finished.
        Triggered by Filebrowser's filebrowser_post_upload signal:
        http://code.google.com/p/django-filebrowser/wiki/signals .
        We'll use this to unzip .zip files in place when/if they're uploaded.
        """

        if kwargs['file'].extension == ".zip":
            # Note: this doesn't test for corrupt zip files. 
            # If encountered, user will get an HTTP Error 
            # and file will remain on the server.

            # We get returned relative path names from Filebrowser
            path = kwargs['path'] 
            thefile = kwargs['file'] 
            
            # Convert file and dir into absolute paths
            fullpath = os.path.join(settings.MEDIA_ROOT,thefile.path_relative)
            dirname = os.path.dirname(fullpath)
            
            # Get a real Python file handle on the uploaded file
            fullpathhandle = open(fullpath, 'r') 

            # Unzip the file, creating subdirectories as needed
            zfobj = zipfile.ZipFile(fullpathhandle)
            for name in zfobj.namelist():
                if name.endswith('/'):
                    try: # Don't try to create a directory if exists
                        os.mkdir(os.path.join(dirname, name))
                    except:
                        pass
                else:
                    outfile = open(os.path.join(dirname, name), 'wb')
                    outfile.write(zfobj.read(name))
                    outfile.close()
                
            # Now try and delete the uploaded .zip file and the 
            # stub __MACOSX dir if they exist.
            try:
                os.remove(fullpath)
            except:
                pass
                
            try:
                osxjunk = os.path.join(dirname,'__MACOSX')
                shutil.rmtree(osxjunk)
            except:
                pass                
            
    # Signal provided by FileBrowser on every successful upload. 
    filebrowser_post_upload.connect(post_upload_callback)

More like this

  1. Handling Image uploading and Delete Old Image in Django by mulianto 3 years, 1 month ago
  2. Delete python compiled files (*.pyc) by kogakure 6 years, 11 months ago
  3. Image uploader to use with file uploader from http://github.com/valums/file-uploader by tgdn 3 years, 5 months ago
  4. Upload a zip file with newforms by kylefox 8 years, 3 months ago
  5. Add a "remove file" field for Image- or FileFields by rodrigoc 6 years, 11 months ago

Comments

Please login first before commenting.