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
- Treat empty value on DateRangeFilter as a filter for non filled dates by kmmbvnr 1 month ago
- Django Settings Assignment Expressions aka Walrus Operator example by webology 2 months ago
- codigo alto nivel by MrRocklion 4 months ago
- Load template from specific app by Krzysiek555 4 months, 3 weeks ago
- PostgreSQL JSON subqueries by dolamroth 4 months, 3 weeks ago