您好,登錄后才能下訂單哦!
使用環(huán)境同上篇django文章。
在django中上傳文件,添加上傳頁面:
安裝pillow:
]# cd py3/django-test1/test5 ]# pip install pillow==3.4.1
如果此前安裝過別的版本,也無所謂,執(zhí)行此命令后會直接覆蓋。
在settings.py文件中配置添加media目錄:
]# vim test5/settings.py ... MEDIA_ROOT = os.path.join(BASE_DIR,'static/upload/')
創(chuàng)建上傳目錄:
]# mkdir static/upload
創(chuàng)建上傳的view視圖函數(shù):
]# vim bookshop/views.py import os from django.shortcuts import render from django.http import HttpResponse from django.conf import settings def index(request): return render(request,'bookshop/index.html') def myExp(request): a1 = int('abc') return HttpResponse('hello_world') def uploadPhoto(request): return render(request,'bookshop/uploadphoto.html') def uploadHandle(request): pic1 = request.FILES['photo1'] picName = os.path.join(settings.MEDIA_ROOT,pic1.name) # return HttpResponse(picName) with open(picName,'wb') as f: for p in pic1.chunks(): f.write(p) return HttpResponse('<img src="/static/upload/%s" />' % pic1.name)
創(chuàng)建上傳的html模板文件:
]# vim templates/bookshop/uploadphoto.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <form action="/uploadHandle" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="photo1"> <br> <input type="submit" value="上傳"> </form> </body> </html>
添加url:
]# vim bookshop/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index), url(r'^myexp$',views.myExp), url(r'^uploadphoto$',views.uploadPhoto), url(r'^uploadHandle$',views.uploadHandle), ]
運行django服務器:
]# python manage.py runserver 192.168.255.70:8000
說明:要上傳的圖片為美女圖
瀏覽器訪問:http://192.168.255.70:8000/uploadphoto
選擇上傳的圖片后,頁面顯示出該圖片:
顯示圖片效果:
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。