import os, json from flask import make_response, send_from_directory, request from flask.helpers import send_file #定义基类 class DocumentOper(): #构造函数,类被初始化时调用 def __init__(self,fileName="", filePath="", fileType=""): print("base init:",fileName,filePath, fileType) self.setFileName(fileName) self.setFilePath(filePath) self.setFileType(fileType) self.setFullPath() #设置文件名 def setFileName(self, fileName): #判断 fileName的值 是不是字符串 if not isinstance(fileName, str): raise Exception('fileName must be string.') self.__fileName = fileName #设置文件路径 def setFilePath(self, filePath): if type(filePath) !=str: raise Exception('filePath must be string.') self.__filePath = filePath #设置文件完整的路径 def setFullPath(self): #upload/docx/xx.docx #return self.__filePath+"/"+self.__fileName return "%s/%s"%(self.__filePath, self.__fileName) def setFileType(self, fileType): if fileType not in ('docx','xlsx','pptx','txt'): raise Exception('不支持的文件格式.') #使用字典形式来识别不同的文件格式,因为python中没有switch..case语句 mimeTypes = { 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' } self.__fileType = fileType self.__mimeType = mimeTypes[fileType] def downloadFile(self): #下载的方法,Blob形式 directory = os.getcwd() #获取当前程序的工作路径 mFilePath = directory.replace('\\','/')+"/"+self.__filePath #response = send_file(self.setFullPath(), mimetype=self.__mimeType, # attachment_filename= self.__fileName, as_attachment=True) response = make_response(send_from_directory(mFilePath,self.__fileName, as_attachment=True)) return response #生成操作,只定义不实现,由各派生类自己完成 def export(self, exportData): try: pass except : pass