用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 configfrom flask import Flask,url_for,redirect,request,render_template,send_from_directoryALLOWED_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_EXTENSIONSdef random_file(filename):"""生成随机文件名:param filename: 文件名:return:随机文件名"""ext=os.path.splitext(filename)[1]#使用uuid生成随机字符new_filename=uuid.uuid4().hex+extreturn 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