django裡上傳圖片的操作

來源:互聯網
上載者:User

標籤:input   media   lib   sharp   表單   bsp   conf   pat   ==   

 

在django裡圖片上傳裡,分為兩種一種是在django的後台上傳圖片,以資料庫的方式上傳,另一種是在html頁面以表單的方式上傳

首先要先安裝下這個包 pip install Pillow==3.4.1

setting裡需要設定 上傳的路徑

MEDIA_ROOT=os.path.join(BASE_DIR,‘static/media‘)

在model裡要設定資料庫

class PicTest(models.Model):

    pic=models.ImageField(upload_to=‘booktest‘)

資料庫裡要有這個欄位

在html 要寫input type=’file’ 這個欄位

在view裡要寫邏輯

還有涉及到要操作setting裡的檔案 需要匯入設定的包

from django.conf import settings
import os

 上傳的圖片都是儲存在   /static/media/booktest/  

接受提交的資料寫到檔案裡  

然後對提交的資料路徑儲存到 資料庫裡

 

 f1=request.FILES.get(‘pic1‘)    path=os.path.join(settings.MEDIA_ROOT,‘booktest‘,f1.name)    with open(path,‘w‘) as pic:        for p in f1.chunks():            pic.write(p)    #儲存資料記錄到資料庫裡    pic1=PicTest()    pic1.pic=‘booktest/%s‘%f1.name    pic1.save()    return HttpResponse(‘ok‘)

  

 

在顯示圖片的時候  view.py   get得到資料庫裡的路徑地址  

這裡要注意  要是使用的all的方式擷取的話 在html裡就需要使用迴圈的方式來顯示圖片

然後在html  <img url= "/static/media/{{p.pic}}

 

第一種以django背景方式提交! 這種用的不多,在這裡也簡單說一下

 

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.