您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
使用环境同上篇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
选择上传的图片后,页面显示出该图片:
显示图片效果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。