在web開發中,檔案上傳與下載下傳是常見的功能,在Django中實作檔案的上傳與下載下傳也非常簡單,實作步驟與其他功能實作類似,1. 建立一個模闆,2. 編寫模闆對應的view函數,3. 配置view與模闆關聯的url。具體實作如下:
1. 建立一個模闆:
建立一個用于上傳檔案的模闆(本文的模闆是基于bootstrap的),内容如下:
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form class="form-inline" role="form" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<input type="submit" value="上傳檔案">
</div>
</form>
</div>
</div>
注意:這個Form表單中必須有屬性 enctype="multipart/form-data",這樣當request方法是POST時,處理這個form的view中才能接受到request.FILES中的檔案資料,可以通過request.FILES['file']來存取。如果不設定這個屬性,request.FILES則為空。
2. 編寫模闆對應的view函數
def upload(request):
if request.method=="POST":
handle_upload_file(request.FILES['file'],str(request.FILES['file']))
return HttpResponse('Successful') #此處簡單傳回一個成功的消息,在實際應用中可以傳回到指定的頁面中
return render_to_response('course/upload.html')
def handle_upload_file(file,filename):
path='media/uploads/' #上傳檔案的儲存路徑,可以自己指定任意的路徑
if not os.path.exists(path):
os.makedirs(path)
with open(path+filename,'wb+')as destination:
for chunk in file.chunks():
destination.write(chunk)
3. 配置相應的URL;
在urls.py檔案中配置相應的url,
url(r'^upload/$',views.upload,name='upload'),
經過上述三個步驟後,我們就寫好檔案上傳的功能,下面測試一下吧:
啟動開發伺服器後,通路相應的upload頁面,頁面如下:
點選【選擇檔案】按鈕,打開想要上傳的檔案,然後點選【上傳檔案】按鈕,就可以将檔案上傳到指定的檔案夾中了。
相關的參考文章:
http://www.cnblogs.com/linjiqin/p/3731751.html
http://my.oschina.net/yushulx/blog/469802