Django文件上傳與下載(FileFlid)
本文實例為大家分享了Django文件上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下
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'] #寫入數(shù)據(jù)庫 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>
上傳成功!
數(shù)據(jù)庫中是這么個情況:
接下來是下載
我的文件目錄是:
要想下載你首先要知道,你上傳的東西到了哪個目錄,涉及到兩個地方:
MEDIA_ROOT = HERE
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pyinstaller?pathex參數(shù)引發(fā)打包no?module?name異常
這篇文章主要為大家介紹了一個關(guān)于pyinstaller的?pathex?參數(shù)所引發(fā)的打包執(zhí)行報no?module?name的異常錯誤解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05pytorch中交叉熵損失函數(shù)的使用小細節(jié)
這篇文章主要介紹了pytorch中交叉熵損失函數(shù)的使用細節(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02使用Python進行數(shù)據(jù)可視化實現(xiàn)引人注目的視覺效果
這篇文章主要介紹了使用Python進行數(shù)據(jù)可視化實現(xiàn)引人注目的視覺效果,您將了解基本的數(shù)據(jù)可視化概念,以及如何創(chuàng)建各種引人注目的圖表和圖形,從而更好地理解和呈現(xiàn)數(shù)據(jù)2023-04-04給大家整理了19個pythonic的編程習慣(小結(jié))
這篇文章主要介紹了給大家整理了19個pythonic的編程習慣(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09Python3.6簡單操作Mysql數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了Python3.6簡單操作Mysql數(shù)據(jù)庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09