Flask实现图⽚的上传、下载及展⽰⽰例代码
⽤Flask处理图⽚⾮常容易,这⼀篇学习⼀下图⽚的上传、下载及展⽰。还是以实例代码演⽰为主。
⾸先,实现⼀个简单的上传(过程中未做任何处理,只是为了演⽰)
点击选择图⽚,输⼊李四:
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form method="post" action="localhost:5000/up_photo" enctype="multipart/form-data">
<input type="file" size="30" name="photo"/>
<br>
<input type="text" class="txt_input" name="name" />
<input type="submit" value="提交信息" class="button-new" />
</form>
</div>
</body>
</html>
后台接收的路由代码:
basedir = os.path.abspath(os.path.dirname(__file__))
@ute('/up_photo', methods=['post'])
def up_photo():
img = ('txt_photo')
username = ("name")
path = basedir+"/static/photo/"
file_path = path+img.filename
img.save(file_path)
print '上传头像成功,上传的⽤户是:'+username
return render_template('index.html')
此时,我们查看static/photo时,已经可以看到我们点击上传的图⽚了。
以上是最简单的⼀个⽂件上传⽰例,我们实际使⽤中基本不可能这样去写,通常会做⼀些处理。例如:上传后做图⽚名称唯⼀性的处理、限制上传⽂件的类型、⽆论上传成功或者失败,都去做⼀些返回提⽰等等。
限制上传⽂件类型,例如,我们希望⽤户上传的⽂件为图⽚类型
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
上⾯的代码⽚段通过截取上传⽂件的后缀名,判断是否是属于我们期望⽤户上传的类型。更改上传图⽚名称,防⽌重名
这⾥我们使⽤⽇期加随机数⽣成图⽚名,做⼀个⽣成字符串的⼯具类
#-*-coding:utf-8-*-
import datetime
import random
class Pic_str:
def create_uuid(self): #⽣成唯⼀的图⽚的名称字符串,防⽌图⽚显⽰时的重名问题
nowTime = w().strftime("%Y%m%d%H%M%S"); # ⽣成当前时间
randomNum = random.randint(0, 100); # ⽣成的随机整数n,其中0<=n<=100
if randomNum <= 10:
randomNum = str(0) + str(randomNum);
uniqueNum = str(nowTime) + str(randomNum);
return uniqueNum;
当我们点击图⽚上传,选择图⽚点击提交后,页⾯返回提⽰信息如下图:
此时看我们⼯程下的upload⽂件夹,唯⼀名称的图⽚已经上传成功
图⽚的下载
@ute('/download/<string:filename>', methods=['GET'])
def download(filename):
hod == "GET":
if os.path.isfile(os.path.join('upload', filename)):
return send_from_directory('upload', filename, as_attachment=True)
pass
getsavefilename图⽚的展⽰
# show photo
@ute('/show/<string:filename>', methods=['GET'])
def show_photo(filename):
file_dir = os.path.join(basedir, fig['UPLOAD_FOLDER'])
hod == 'GET':
if filename is None:
pass
else:
image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
response = make_response(image_data)
response.headers['Content-Type'] = 'image/png'
return response
else:
pass
完整⽰例代码
#encoding:utf-8
#!/usr/bin/env python
from werkzeug.utils import secure_filename
from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort import time
import os
from strUtil import Pic_str
import base64
app = Flask(__name__)
UPLOAD_FOLDER = 'upload'
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@ute('/upload')
def upload_test():
return render_template('up.html')
# 上传⽂件
@ute('/up_photo', methods=['POST'], strict_slashes=False)
def api_upload():
file_dir = os.path.join(basedir, fig['UPLOAD_FOLDER'])
if not ists(file_dir):
os.makedirs(file_dir)
f = request.files['photo']
if f and allowed_file(f.filename):
fname = secure_filename(f.filename)
print fname
ext = fname.rsplit('.', 1)[1]
new_filename = Pic_str().create_uuid() + '.' + ext
f.save(os.path.join(file_dir, new_filename))
return jsonify({"success": 0, "msg": "上传成功"})
else:
return jsonify({"error": 1001, "msg": "上传失败"})
@ute('/download/<string:filename>', methods=['GET'])
def download(filename):
hod == "GET":
if os.path.isfile(os.path.join('upload', filename)):
return send_from_directory('upload', filename, as_attachment=True)
pass
# show photo
@ute('/show/<string:filename>', methods=['GET'])
def show_photo(filename):
file_dir = os.path.join(basedir, fig['UPLOAD_FOLDER'])
hod == 'GET':
if filename is None:
pass
else:
image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
response = make_response(image_data)
response.headers['Content-Type'] = 'image/png'
return response
else:
pass
if __name__ == '__main__':
app.run(debug=True)
基本⽰例就以上这些了!
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。