Django檔案上傳與下載(FileFlid)
阿新 • • 發佈:2020-01-09
本文例項為大家分享了Django檔案上傳與下載的具體程式碼,供大家參考,具體內容如下
Django1.4
首先是上傳:
#settings.py
MEDIA_ROOT = HERE#定義一個完整路徑給 MEDIA_ROOT 以便讓 Django在此處儲存上傳檔案
MEDIA_URL = 'media'#定義 MEDIA_URL 作為該目錄的公共 URL,要確保該目錄對 WEB 伺服器使用者帳號是可寫的
#model.py #coding=utf-8 from django.db import models class User(models.Model): username = models.CharField(max_length = 30) headImg = models.FileField(upload_to = 'update/%Y%m%d') def __unicode__(self): return self.username
#view.py #coding=utf-8 from django.shortcuts import render_to_response from django import forms from django.http import HttpResponse from django.template import RequestContext from disk.models import User # Create your views here. class UserForm(forms.Form): username = forms.CharField() headImg = forms.FileField() def register(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): #獲取表單資訊 username = uf.cleaned_data['username'] headImg = uf.cleaned_data['headImg'] #寫入資料庫 user = User() user.username = username user.headImg = headImg user.save() return HttpResponse('upload ok!') else: uf = UserForm() ur= User.objects.order_by('id') return render_to_response('register.html',{'uf':uf},context_instance=RequestContext(request))
前臺使用{{uf.as_ul}}來展示form,如下:
#register.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <a href="update/20140711/005zEPW4jw1eg3js7sil3g30500824al.gif" rel="external nofollow" >gao</a> <body> <h1>register</h1> <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{uf.as_ul}} <input type="submit" value="ok" /> </form> </body> </html>
上傳成功!
資料庫中是這麼個情況:
接下來是下載
我的檔案目錄是:
要想下載你首先要知道,你上傳的東西到了哪個目錄,涉及到兩個地方:
MEDIA_ROOT = HERE
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。