标签:end 路径 val head join art ase put Enctype
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) 显示图片
标签:end 路径 val head join art ase put Enctype
原文地址:https://www.cnblogs.com/gaota1996/p/10448511.html