django之上传文件
作者:互联网
使用环境同上篇django文章。
在django中上传文件,添加上传页面:
安装pillow:
]# cd py3/django-test1/test5 ]# pip install pillow==3.4.1
如果此前安装过别的版本,也无所谓,执行此命令后会直接覆盖。
在settings.py文件中配置添加media目录:
]# vim test5/settings.py ... MEDIA_ROOT = os.path.join(BASE_DIR,'static/upload/')
创建上传目录:
]# mkdir static/upload
创建上传的view视图函数:
]# 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)
创建上传的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
选择上传的图片后,页面显示出该图片:
显示图片效果:
标签:文件,views,url,之上,request,django,import,上传 来源: http://blog.51cto.com/linsj/2345628