表單上傳的文件對(duì)象存儲(chǔ)在類(lèi)字典對(duì)象request.FILES中,表單格式需為multipart/form-data
| 12 | <form enctype="multipart/form-data"method="post"action="/foo/"><input type="file"name="image"/> |
request.FILES中的鍵來(lái)自于表單中的<input type="file" name="" />的name值:
| 1 | img=request.FILES['image'] |
request.FILES中的值均為UploadedFile類(lèi)文件對(duì)象。
UploadedFile是類(lèi)文件對(duì)象,具有以下方法和屬性:
UploadedFile.read()
讀取整個(gè)上傳文件的數(shù)據(jù),文件較大時(shí)慎用。
UploadedFile.multiple_chunks(chunk_size=None)
判斷文件是否足夠大,一般為2.5M
UploadedFile.chunks(chunk_size=None)
返回一個(gè)生成器對(duì)象,當(dāng)multiple_chunks()為T(mén)rue時(shí)應(yīng)該使用這個(gè)方法來(lái)代替read().
UploadedFile.name
上傳文件的name。
UploadedFile.size
上傳文件的大小。
UploadedFile.content_type
上傳文件時(shí)的content_type報(bào)頭,例如(e.g. text/plain or application/pdf).
UpladedFile.charset
編碼
想將上傳的文件存儲(chǔ)在本地時(shí):
| 1234 | f=request.FILES['image']withopen('some/file/name.txt','wb+') as destination: forchunk inf.chunks(): destination.write(chunk) |
使用Form處理上傳文件
也可以使用django自帶的form來(lái)處理上傳文件。
先創(chuàng)建帶FileFiled或者ImageFiled的Form:
| 123456 | # In forms.py...from django import forms classUploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() |
用Form處理:
| 1 | >>> f =UploadFileFormt(request.POST, request.FILES) |
view函數(shù):
| 123456789101112131415161718 | from django.httpimport HttpResponseRedirectfrom django.shortcutsimport render_to_responsefrom .forms import UploadFileForm def handle_uploaded_file(f): withopen('some/file/name.txt','wb+') as destination: forchunk inf.chunks(): destination.write(chunk) def upload_file(request): ifrequest.method == 'POST': form = UploadFileForm(request.POST, request.FILES) ifform.is_valid(): handle_uploaded_file(request.FILES['file']) returnHttpResponseRedirect('/success/url/') else: form = UploadFileForm() returnrender_to_response('upload.html', {'form': form}) |
如果創(chuàng)建了一個(gè)帶FileField或者ImageField域的Model,需要將上傳文件存儲(chǔ)到Model的FileFIeld域。
比如,使用nicEdit文本編輯器時(shí),需要存儲(chǔ)上傳的文件,建立Model:
| 1234 | from django.dbimport models classNicEditImage(models.Model): image = models.ImageField(upload_to='nicedit/%Y/%m/%d') |
創(chuàng)建ModelForm:
| 12345 | from django import forms classNicEditImageForm(forms.ModelForm): classMeta: model = NicEditImage |
view:
| 1234567891011121314151617181920212223 | def upload(request): ifnot request.user.is_authenticated(): json = simplejson.dumps({ 'success': False, 'errors': {'__all__':'Authentication required'}}) returnHttpResponse(json, mimetype='application/json') form = NicEditImageForm(request.POST or None, request.FILES or None) ifform.is_valid(): image = form.save() #保存Form和Model json = simplejson.dumps({ 'success': True, 'upload': { 'links': { 'original': image.image.url}, 'image': { 'width': image.image.width, 'height': image.image.height} } }) else: json = simplejson.dumps({ 'success': False,'errors': form.errors}) returnHttpResponse(json, mimetype='application/json') |
當(dāng)然也可以手動(dòng)存儲(chǔ)文件到Model的文件域:
| 123456789101112131415 | from django.httpimport HttpResponseRedirectfrom django.shortcutsimport renderfrom .forms import UploadFileFormfrom .modelsimport ModelWithFileField def upload_file(request): ifrequest.method == 'POST': form = UploadFileForm(request.POST, request.FILES) ifform.is_valid(): instance = ModelWithFileField(file_field=request.FILES['file']) #保存文件到FileField域 instance.save() returnHttpResponseRedirect('/success/url/') else: form = UploadFileForm() returnrender(request, 'upload.html', {'form': form}) |
想獲得更大自由度時(shí),可以全手動(dòng)處理。
| 123456 | from django.dbimport models classCar(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars') |
Model的FileField有以下屬性:
| 123456789 | >>> car = Car.objects.get(name="57 Chevy")>>> car.photo<ImageFieldFile: chevy.jpg>>>> car.photo.nameu'cars/chevy.jpg'>>> car.photo.pathu'/media/cars/chevy.jpg'>>> car.photo.urlu'http://media.example.com/cars/chevy.jpg' |
Model的FileField是一個(gè)File對(duì)象,除了具有File對(duì)象的各種方法外,還有一個(gè)額外的save()方法:
FieldFile.save(name, content, save=True)
name為存儲(chǔ)名字,content為File或者File子類(lèi)的實(shí)例
| 12 | >>> car.photo.save('myphoto.jpg', content, save=False)>>> car.save() |
類(lèi)似于
| 1 | >>> car.photo.save('myphoto.jpg', content, save=True) |
手動(dòng)存儲(chǔ):
| 123456 | from django.core.files.baseimport ContentFilephoto=request.FILES.get('photo','')if photo: file_content = ContentFile(photo.read()) #創(chuàng)建File對(duì)象 car.photo.save(photo.name, file_content) #保存文件到car的photo域 car.save() |
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注