processing an image upload form in django: when to use save() vs chunks() vs cleaned_data?

两盒软妹~` 提交于 2019-12-04 10:23:25

Chunking is needed when file is bigger than settings.FILE_UPLOAD_MAX_MEMORY_SIZE (default 2.5M in django 1.2)

Take a look at django.core.files.storage.FileSystemStorage class. It's save() method does the chunk-wise saving job for you and does the proper file locking.

storage = FileSystemStorage(
                    location = '/var/www/site/upfiles', 
                    base_url = '/upfiles'
                  )


content = request.FILES['the_file']
name = storage.save(None, content) #you can use some suggested name instead of
                                   #None. content.name will be used with None
url = storage.url(name)   #<-- get url for the saved file

In the older versions of django (e.g in 1.0) there was a defect in generation of file names. It kept adding _ to file names and the uploaded file name got longer and longer if you upload the same file repeatedly. This seems to be fixed in version 1.2.

By accessing request.FILES['file'] directly, you're bypassing any processing that your UploadFileForm is doing (you don't even need a form class to handle files like that). form.cleaned_data['file'] would access the processed (and cleaned, if you added a clean method) form data. You could also access the request.POST dictionary directly, instead of the form data. Unless you have a good reason to, it's better to use the cleaned form data.

In the example you gave, there was also a model being used (which is what the save() method was being called on), and it was the model's field that was handling the file access. If you want to save information about your uploaded files in a database, that's the way to go.

You can use the built-in file storage API for saving files: http://docs.djangoproject.com/en/dev/ref/files/storage/#ref-files-storage.

Also, it's not a good idea to simply call open(MEDIA_ROOT + '/images/'+file.name, 'wb+'), with the user-specified file name. That's just asking for directory traversal or other issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!