用GET、POST请求上传图片并呈现出来
首先还是创建文件上传的模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="avatar">上传图片</label>
<input type="file" id="avatar" name="avatar" value="">
</div>
<button type="submit">提交</button>
</form>
</body>
</html>
然后需要定义几个函数:
upload():路由函数,接收GET请求时,显示模板文件内容,接收post请求时,上传图片
allowed_file():检测上传的文件是否满足设置的类型
random_file():为上传的文件重新创建随机的不重复文件名
uploaded_file():显示图片内容
import os.path
import uuid
import config
from flask import Flask,url_for,redirect,request,render_template,send_from_directory
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif','PNG', 'JPG', 'JPEG', 'GIF',}
app=Flask(__name__)
UPLOAD_FOLDER = os.path.join(app.root_path,'uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/upload',methods=['GET','POST'])
#创建路由函数,接收GET请求时,显示模板文件内容,接收post请求时,上传图片
def upload():
"""
#头像上传表单页面
:return:
"""
if request.method=='POST':
#接受头像字段
avatar=request.files['avatar']
#判断头像是否上传
if avatar and allowed_file(avatar.filename):
filename=random_file(avatar.filename)
avatar.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return redirect(url_for('uploaded_file',filename=filename))
return render_template('upload.html')
def allowed_file(filename):
"""
#判断上传文件类型是否允许
:param filename 文件名
:return: 布尔值 TRUE or False
"""
print(filename)
return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
def random_file(filename):
"""
生成随机文件名
:param filename: 文件名
:return:随机文件名
"""
ext=os.path.splitext(filename)[1]
#使用uuid生成随机字符
new_filename=uuid.uuid4().hex+ext
return new_filename
@app.route('/uploads/<filename>')
def uploaded_file(filename):
"""
显示上传头像
:param filename:文件名
:return: 真实文件路径
"""
return send_from_directory(app.config['UPLOAD_FOLDER'],filename)
if __name__=='__main__':
app.run(
debug=True
)
需要单独设置的内容:
ALLOWED_EXTENSIONS:文件后缀类型
UPLOAD_FOLDER:上传文件的路径,如果不设置,会报错:
KeyError: 'UPLOAD_FOLDER'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif','PNG', 'JPG', 'JPEG', 'GIF',}
UPLOAD_FOLDER = os.path.join(app.root_path,'uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
文章来源地址https://www.toymoban.com/news/detail-627723.html
文章来源:https://www.toymoban.com/news/detail-627723.html
到了这里,关于【Python】Web学习笔记_flask(3)——上传文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!