美文网首页
python实现文件上传

python实现文件上传

作者: KS保 | 来源:发表于2021-09-01 09:51 被阅读0次

    用于flask框架中,用户上传指定格式的图片到本地服务器

    # -*- coding: utf-8 -*-
    from flask import request
    from werkzeug.utils import secure_filename
    from random import Random
    import time
    import os
    
    
    class Uploader:
        #错误消息
        __stateMap = {
            'SUCCESS': 'SUCCESS',
            'ERROR_TMP_FILE': '临时文件错误',
            'ERROR_TMP_FILE_NOT_FOUND': '找不到临时文件',
            'ERROR_SIZE_EXCEED': '文件大小超出网站大小',
            'ERROR_TYPE_NOT_ALLOWED': '文件类型不允许',
            'ERROR_CREATE_DIR': '目录创建失败',
            'ERROR_DIR_NOT_WRITEABLE': '目录没有写权限',
            'ERROR_FILE_MOVE': '文件保存时出错',
            'ERROR_FILE_NOT_FOUND': '找不到上传文件',
            'ERROR_FILE_NOT_FILEPATH': '未提供保存目录',
            'ERROR_WRITE_CONTENT': '写入文件错误',
            'ERROR_UNKNOWN': '未知错误'
        }
    
        @classmethod
        def randomString(cla, randomlength = 8):
            str = ''
            chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
            length = len(chars) - 1
            random = Random()
            for i in range(randomlength):
                str+=chars[random.randint(0, length)]
            return str
        
        def __init__(self, fileField, config = None):
            self.__fileField = fileField
            self.__config = config or {}
            self.__uploadFile = None
            self.__stateInfo = None
            self.__name = None
            self.__size = None
            self.__upFile()
    
        def getFileInfo(self):
            if self.__stateInfo == 'SUCCESS':
                return {'state': self.__stateInfo, 'name': self.__newName, 'path': self.__filePath,'oldname':self.__name, 'size':self.__size}
            return {'state': self.__stateInfo}
    
        def __upFile(self):
            uploadFile = self.__uploadFile = request.files.get(self.__fileField)
            if not uploadFile:
                self.__stateInfo = self.__stateMap['ERROR_FILE_NOT_FOUND']
                return False
    
            self.__fileType = self.__getFileExt(uploadFile)
            self.__newName = self.__getFullName(self.__fileType)
            self.__name = request.values.get('name')
            self.__size = request.values.get('size',0, int)
    
            if not self.__checkType(self.__fileType):
                self.__stateInfo = self.__stateMap['ERROR_TYPE_NOT_ALLOWED']
                return False
    
            if not ('filePath' in self.__config) or len(self.__config.get('filePath')) == 0:
                self.__stateInfo = self.__stateMap['ERROR_FILE_NOT_FILEPATH']
                return False
    
            self.__filePath = self.__config.get('filePath')
    
            if self.__filePath[-1] != os.sep:
                self.__filePath = self.__filePath + os.sep
    
            try:
                self.__uploadFile.save(self.__filePath + self.__newName, buffer_size = 1638400)
                self.__stateInfo = self.__stateMap['SUCCESS']
            except Exception as e:
                self.__stateInfo = self.__stateMap['ERROR_FILE_MOVE']
                print(e)
    
        def __checkType(self, type):
            if not 'allowFiles' in self.__config:
                self.__config['allowFiles'] = []
            return type in self.__config['allowFiles']
    
        def __getFullName(self, type):
            if 'fileName' in self.__config:
                return '%s.%s' % (self.__config.get('fileName'), type)
            return '%s.%s' % (str(int(time.time()))+Uploader.randomString(8), str(type))
    
        def __getFileExt(self, uploadFile):
            fileName = secure_filename(uploadFile.filename)
            return fileName[(fileName.rfind('.', 0, len(fileName)) + 1):len(fileName)]
    
    file_path = "xxx"
    uploader = Uploader("file", {"filePath": file_path, "allowFiles": ["jpg", "jpeg", "png", "gif"]})
    

    相关文章

      网友评论

          本文标题:python实现文件上传

          本文链接:https://www.haomeiwen.com/subject/kasmbltx.html