栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python flask文件上传封装

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python flask文件上传封装

1.创建utils文件夹 在utils文件夹下创建myfile.py

# coding=gbk


import os
import uuid
import shutil


class MyFile():
    def __init__(self, upload_dir='./static/upload/'):
        self.up_dir = upload_dir

    # 创建文件夹
    def mk_dir(self, userid):
        # 判断文件夹是否存在 不存在创建
        path = self.up_dir + str(userid) + '/'
        if not os.path.exists(path):
            # 如果该用户文件夹不存在 则创建文件夹
            os.mkdir(path)
    # 重命名
    def rename(self,filename):
        name = os.path.splitext(filename)[1]
        fname = uuid.uuid4().hex + name
        return fname

    # 删除目录及文件
    def remove_file(self, userid):
        path = self.up_dir + str(userid) + '/'
        # 判断文件夹是否存在
        if os.path.exists(path):
            # 存在删除文件夹及下面所有文件
            shutil.rmtree(path)

    # 删除整个目录
    def remove_dir(self, userid):
        os.rmdir(self.up_dir + str(userid))  # 只能删除为空得文件夹

    # 查看文件
    def list_file(self, id):
        list = []
        mylist = os.listdir(self.up_dir + str(id))
        for i in mylist:
            list.append(i)
        return list

mf = MyFile()

2.蓝图接口

from utils.myfile import mf
# 记得注册蓝图
@bp_workf.route('/upload/', methods=['POST'])
def upload():
    file = request.files['file']
    wid = int(request.form.get('id'))

    # 文件重命名
    newfile = mf.rename(file.filename)
    path = './static/upload/' + str(wid)
    if not os.path.exists(path):  # 文件路径不存在
        # 根据工作流id 创建文件夹
        mf.mk_dir(wid)
    # 保存
    try:
        file.save(os.path.join(path, newfile))
        # osfile
        path1 = '/static/upload/' + str(wid)
        return jsonify({'code': 200, 'msg': '证件上传成功', 'newfile': path1 + '/' + newfile})
    except:
        return jsonify({'code': 200, 'msg': '证件上传失败', })

3.vue前端页面





转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/701285.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号