這個應該是Django的最後一個學習模組了。再深入的就需要到項目裡面去實踐了
Django上傳檔案有兩種方式,一種是傳統的基於IO流的操作,一種是封裝為基於對象的操作。
但是無論哪種操作,都需要先建立上傳檔案的目錄,
一、基於IO流的操作
urls中的配置,基於學習筆記(五)中的表單的提交的blog/param/(?P<id>\d{2})
修改的post方法如下:
def post(req): if req.method == 'POST': form = UserForm(req.POST,req.FILES) if form.is_valid(): print form.cleaned_data print form.cleaned_data['name'] print form.cleaned_data['userImag'].name print form.cleaned_data['userImag'].size #way 1 s = form.cleaned_data['userImag'].read() fb = file('./djangotest/upload/'+form.cleaned_data['userImag'].name,'wb') fb.write(s) fb.close() return HttpResponse('OK') else : return HttpResponse('Failed') else : form = UserForm() return render_to_response('param.html',{'form':form})
對應的param.html如下:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>{{id}}</title></head><body>{{num}}<br/>{{url}}<br/>提交form需要注釋掉settings檔案中MIDDLEWARE_CLASSES的驗證(token驗證)<form action="/blog/post/" method="post" enctype="multipart/form-data"><span style="white-space:pre"></span>{{form.as_p}}<span style="white-space:pre"></span><button type="submit">提交</button></form></body></html>
二、基於對象方式儲存:
首先,配置settings檔案中的
MEDIA_ROOT = './djangotest/'
目的是讓之後的上傳操作的路徑都相對於項目本身的路徑,而不必寫死
增加新的models:
class Files(models.Model): name = models.CharField(max_length=300) f = models.FileField(upload_to='upload/') def __unicode__(self): return self.name
同步資料庫
修改post方法:
def post(req): if req.method == 'POST': form = UserForm(req.POST,req.FILES) if form.is_valid(): print form.cleaned_data print form.cleaned_data['name'] print form.cleaned_data['userImag'].name print form.cleaned_data['userImag'].size #way 1 s = form.cleaned_data['userImag'].read() fb = file('./djangotest/upload/'+form.cleaned_data['userImag'].name,'wb') fb.write(s) fb.close() #way2 f = Files(name=form.cleaned_data['userImag'].name,f=form.cleaned_data['userImag']) f.save() return HttpResponse('OK') else : return HttpResponse('Failed') else : form = UserForm() return render_to_response('param.html',{'form':form})
對應的param.html如下:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>{{id}}</title></head><body>{{num}}<br/>{{url}}<br/>提交form需要注釋掉settings檔案中MIDDLEWARE_CLASSES的驗證(token驗證)<form action="/blog/post/" method="post" enctype="multipart/form-data"><span style="white-space:pre"></span>{{form.as_p}}<span style="white-space:pre"></span><button type="submit">提交</button></form></body></html>