django实现图片上传和访问Python

无敌的宇宙
无敌的宇宙
擅长邻域:Java,HTML,JavaScript,MySQL,支付,退款,图片上传

分类: python 标签: django实现图片上传和访问Python

2024-08-15 21:23:24 528浏览

django实现图片上传和访问Python

图片工具类:/app01/untils/uploadFileUntil.py

import os
import random


def upload( file,package):

format=file.name[file.name.rfind('.'):len(file.name)]
print(format)
abpath = os.path.abspath(os.path.dirname(__file__)).replace('untils','')+'static/upload/'+package+'/'
if not os.path.exists(abpath):
os.makedirs(abpath)

fname=''
for t in range(1,20):
fname+=str(random.randint(1,10))
abpathfname=abpath+fname+format
f=open(abpathfname,'wb')
for chunk in file.chunks():
f.write(chunk)
f.close()
return '/upload/'+package+'/'+fname+format

def delfile( path ):
abpath = os.path.abspath(os.path.dirname(__file__)).replace('untils','')+'/static'
f=abpath+path
if(os.path.exists(f)):
print(f)
os.remove(f)

if __name__ == '__main__':
delfile('/upload/faceimg/1914610510521038641376.jpg')

上传html

<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/uploadimg" role="form" style="width: 500px;margin:100px auto">
{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 control-label">图片</label>
<div class="col-sm-10">
<input type="file" name="file" class="form-control" required>
</div>
</div>


<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">登录</button>
<p style="color: red">{{msg}}</p>
</div>
</div>
</form>

views.py

def uploadimg(request ):
if request.method=='GET':
return render(request,"upload.html" )
file=request.FILES.get('file')
faceimg=uploadFileUntil.upload(file,'faceimg')
return render(request,"uploadsucc.html",{'faceimg':faceimg} )

网页如何访问

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.net/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.net/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<img src="{% static faceimg %}">
</body>
</html>

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695