django后台处理前端上传和显示图片

时间:2022-04-19 12:12:42
 

1:项目根目录存放图片的目录

2:settings.py  添加

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

3:url.py 添加后面路径自己定义

import django.views.static
 url(r'^media/(?P<path>.*)',django.views.static.serve,{'document_root':'C:\Users\Administrator\PycharmProjects\itracnew\itrac\media'}),

4:views.py

from xxx import settings
def test(request):
if request.method =="POST":
f1 = request.FILES['pic']
fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name)
picname = fname.split(".")[0]+".png"
with open(picname, 'wb') as pic:
for c in f1.chunks():
pic.write(c)
print("picture OK",picname)
post_pic = str(picname.split("/")[1])

5:html文件

  <div class="control-group">
<div class="input-group">
<span class="input-group-addon control-label" for="issue">上传图片(可选):</span>
<input type="file" name="pic" id="pic" accept="image/*" class="upload-input">
</div>
</div>

6:我在models文件加了一个字段方便存名字调用

    pict = models.CharField(max_length=100,null=True,blank=True)