django檔案上傳

來源:互聯網
上載者:User

標籤:圖片   Enctype   com   ase   settings   ror   ati   dia   安裝包   

django檔案上傳

-------------------上傳圖片-------------------
1、model中定義屬性類型為models.ImageField類型
pic=models.ImageField(upload_to=‘images/upload/‘)

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

3、圖片儲存路徑
1、在項目根目錄下建立static檔案夾

2、圖片上傳後,會被儲存到“/static/images/upload/圖片檔案”

3、開啟settings.py檔案,增加media_root項
MEDIA_ROOT=os.path.join(BASE_DIR,"static")

4、使用django後台管理,遇到ImageField類型的屬性會出現一個file框,完成檔案上傳

5、執行個體:
<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")

django檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.