python3 flask实现文件上传功能
程序员文章站
2023-10-28 10:34:28
本文实例为大家分享了python3-flask文件上传操作的具体代码,供大家参考,具体内容如下
# -*- coding: utf-8 -*-
import o...
本文实例为大家分享了python3-flask文件上传操作的具体代码,供大家参考,具体内容如下
# -*- coding: utf-8 -*- import os import uuid import platform from flask import flask,request,redirect,url_for from werkzeug.utils import secure_filename if platform.system() == "windows": slash = '\\' else: platform.system()=="linux" slash = '/' upload_folder = 'upload' allow_extensions = set(['html', 'htm', 'doc', 'docx', 'mht', 'pdf']) app = flask(__name__) app.config['upload_folder'] = upload_folder #判断文件夹是否存在,如果不存在则创建 if not os.path.exists(upload_folder): os.makedirs(upload_folder) else: pass # 判断文件后缀是否在列表中 def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in allow_extensions @app.route('/',methods=['get','post']) def upload_file(): if request.method =='post': #获取post过来的文件名称,从name=file参数中获取 file = request.files['file'] if file and allowed_file(file.filename): # secure_filename方法会去掉文件名中的中文 filename = secure_filename(file.filename) #因为上次的文件可能有重名,因此使用uuid保存文件 file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1] file.save(os.path.join(app.config['upload_folder'],file_name)) base_path = os.getcwd() file_path = base_path + slash + app.config['upload_folder'] + slash + file_name print(file_path) return redirect(url_for('upload_file',filename = file_name)) return ''' <!doctype html> <title>upload new file</title> <h1>upload new file</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=upload> </form> ''' if __name__ == "__main__": app.run(host='0.0.0.0',port=5000)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。