Django實(shí)現(xiàn)圖片上傳功能步驟解析
1.首先是html頁(yè)面的form表單的三大屬性,action是提交到哪,method是提交方式,enctype只要有圖片上傳就要加這個(gè)屬性
Django框架自帶csrf_token ,所以需要在前端頁(yè)面也生成csrf_token字符串,來(lái)驗(yàn)證真實(shí)客戶
<form action='/pic_upload/' method='POST' enctype='multipart/form-data'> {% csrf_token %} <input type='file' name='file'> <input type='submit' value='提交'> </form>
2.如下是上傳圖片的接口:
def pic_upload(request): if request.method == 'GET': return render(request,'helloapp/pic_upload.html',locals()) if request.method == 'POST': error = '' fp = request.FILES.get('file') # fp 獲取到的上傳文件對(duì)象 if fp: path = os.path.join(STATICFILES_DIRS[0],’image/’ + fp.name) # 上傳文件本地保存路徑, image是static文件夾下專門存放圖片的文件夾 # fp.name #文件名 #yield = fp.chunks() # 流式獲取文件內(nèi)容 # fp.read() # 直接讀取文件內(nèi)容 if fp.multiple_chunks(): # 判斷上傳文件大于2.5MB的大文件# 為真file_yield = fp.chunks() # 迭代寫入文件with open(path,’wb’) as f: for buf in file_yield: # for情況執(zhí)行無(wú)誤才執(zhí)行 else f.write(buf) else: print('大文件上傳完畢') else:with open(path,’wb’) as f: f.write(fp.read())print('小文件上傳完畢') models.ImgPath.objects.create(path=(’image/’ + fp.name)) # image是static文件夾下專門存放圖片的文件夾 else: error = '文件上傳為空' return render(request,'helloapp/pic_upload.html',locals()) return redirect('helloapp/pic_index/') # 重定向到首頁(yè)
3.做個(gè)圖片展示的頁(yè)面,對(duì)圖片展示對(duì)應(yīng)的接口傳過(guò)來(lái)的參數(shù)加以判斷
{% for img in imgs %} <img src='http://m.lshqa.cn/bcjs/{% static img.path %}'> {% empty %} <h1>您沒(méi)有上傳任何圖片</h1> {% endfor %}
4.圖片展示的接口:
def pic_index(request): imgs = models.ImgPath.objects.all() return render(request,’helloapp/pic_index.html’,locals())
至此,Django中一個(gè)簡(jiǎn)單的圖片上傳到展示就做好了
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何對(duì)php程序中的常見(jiàn)漏洞進(jìn)行攻擊2. PHP循環(huán)與分支知識(shí)點(diǎn)梳理3. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能4. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)5. JavaWeb Servlet中url-pattern的使用6. Spring MVC+ajax進(jìn)行信息驗(yàn)證的方法7. jsp EL表達(dá)式詳解8. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算
