上传图片示例
Posted gaota1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传图片示例相关的知识,希望对你有一定的参考价值。
pip install pillow==3.4.1
settings.py
xxxxxxxxxxx
STATIC_URL = ‘/static/‘
STATICFILES_DIRS = [
os.path.join(BASE_DIR, ‘static‘)
]
MEDIA_ROOT = os.path.join(BASE_DIR, ‘static/media‘)
views.py
from django.shortcuts import render, HttpResponse import os from django.conf import settings def uploadPic(request): return render(request, ‘booktest/uploadPic.html‘) def upload_handle(request): pic1 = request.FILES[‘pic1‘] picName = os.path.join(settings.MEDIA_ROOT, pic1.name) return HttpResponse(picName)
uploadPic.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload_handle" method="post" enctype="multipart/form-data"> <input type="file" name="pic1"><br> <input type="submit" value="上传"> </form> </body> </html>
添加url
查看结果
修改views.py
from django.shortcuts import render, HttpResponse import os from django.conf import settings def uploadPic(request): return render(request, ‘booktest/uploadPic.html‘) def upload_handle(request): pic1 = request.FILES[‘pic1‘] picName = os.path.join(settings.MEDIA_ROOT, pic1.name) # 定义图片存到哪里去,在settings.py找到MEDIA_ROOT里面的路径
with open(picName, ‘wb+‘) as pic: for c in pic1.chunks(): pic.write(c) return HttpResponse(picName) # 显示路径
# return HttpResponse(‘<img src="/static/media/%s">‘ %pic1.name) 显示图片
以上是关于上传图片示例的主要内容,如果未能解决你的问题,请参考以下文章
Android - 应用程序启动时片段 onCreate 崩溃
uniapp产品编辑页-图片上传后回显编辑-组件uni-file-picker显示之前已上传的图片 + 头像图片原地覆盖上传示例
uniapp产品编辑页-图片上传后回显编辑-组件uni-file-picker显示之前已上传的图片 + 头像图片原地覆盖上传示例