首頁技術(shù)文章正文

django文件上傳

更新時間:2018-08-09 來源:黑馬程序員 瀏覽量:

1、model中定義屬性類型為models.ImageField類型
pic=models.ImageField(upload_to='images/upload/')

2、如果屬性類型為ImageField需要安裝包Pilow
pip install Pillow==3.4.1

3、圖片存儲路徑
1、在項目根目錄下創(chuàng)建static文件夾

2、圖片上傳后,會被保存到“/static/images/upload/圖片文件”

3、打開settings.py文件,增加media_root項
MEDIA_ROOT=os.path.join(BASE_DIR,"static")

4、使用django后臺管理,遇到ImageField類型的屬性會出現(xiàn)一個file框,完成文件上傳

5、實(shí)例:
<html>
<head>
<title>文件上傳</title>
</head>
<body>
<form method="post" action="upload/" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="pic"/><br>
<input type="submit" value="上傳">
</form>
</body>
</html>

#-------------后臺view接收處理
def upload(request):
if request.method == "POST":
f1 = request.FILES['pic']
fname = '/static/images/upload/%s' % f1.name
with open(fname, 'w') as pic:
for c in f1.chunks():
pic.write(c)
return HttpResponse("ok")
else:
return HttpResponse("error")



作者:黑馬程序員人工智能+python培訓(xùn)學(xué)院
首發(fā):http://python.itheima.com/

分享到:
在線咨詢 我要報名
和我們在線交談!