我已經用下面的代碼成功上傳的圖片:在django中處理圖片上傳表單:何時使用save()vs chunks()vs cleaned_data?
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.
我注意到他們的代碼使用save()和cleaned_data。是否有必要遍歷塊並寫入目標文件夾,如文檔中的示例一樣?我必須使用cleared_data嗎?試圖找出上傳文件的最有效方法,我已經看到了很多不同的方式來做這件事。非常感謝您的幫助。當文件大於settings.FILE_UPLOAD_MAX_MEMORY_SIZE
(在Django 1.2默認2.5M)
看看django.core.files.storage.FileSystemStorage
類需要