码迷,mamicode.com
首页 > Web开发 > 详细

上传图片示例

时间:2019-02-28 10:18:03      阅读:222      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!