在 django 中处理图像上传表单:何时使用 save()、chunks() 和 clean_data?

2024-06-19

我已经使用以下代码成功上传了图像:

views.py

from django.conf.urls.defaults import *
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import template
from django.template import RequestContext

from mysite.uploadr.forms import UploadFileForm

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.handle_uploaded_file(request.FILES['file'])
            return HttpResponse(template.Template('''
                        <html><head><title>Uploaded</title></head> <body>
                        <h1>Uploaded</h1>
                        </body></html>
                        '''
                        ).render( template.Context({}))
                    )
    else:  
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form}, context_instance=RequestContext(request))

forms.py

from django import forms
from settings import MEDIA_ROOT

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length = 50)
    file = forms.FileField()

    def handle_uploaded_file(self,file):
        #print type(file), "file.name=",file.name
        #print dir(file)
        destination = open(MEDIA_ROOT + '/images/'+file.name, 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)

我想更进一步,将图像与正在上传的用户关联起来。我看过一些例子并且喜欢这篇文章中的技术:https://stackoverflow.com/questions/3348013/django-image-file-uploads。 https://stackoverflow.com/questions/3348013/django-image-file-uploads

我注意到他们的代码使用 save() 和 clean_data。是否不需要像文档中的示例那样迭代块并写入目标文件夹?我必须使用cleaned_data吗?只是想找出最有效的上传文件的方法,我已经看到了很多不同的方法。非常感谢您的帮助。


当文件大于时需要分块settings.FILE_UPLOAD_MAX_MEMORY_SIZE(django 1.2 中默认为 2.5M)

看一眼django.core.files.storage.FileSystemStorage http://code.djangoproject.com/browser/django/trunk/django/core/files/storage.py班级。它的 save() 方法为您执行按块保存的工作并执行正确的文件锁定。

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

在旧版本的 django 中(例如 1.0),文件名的生成存在缺陷。一直在添加_如果重复上传同一个文件,上传的文件名会变得越来越长。这似乎在 1.2 版本中得到了修复。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 django 中处理图像上传表单:何时使用 save()、chunks() 和 clean_data? 的相关文章

随机推荐