documentoper.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import os, json
  2. from flask import make_response, send_from_directory, request
  3. from flask.helpers import send_file
  4. #定义基类
  5. class DocumentOper():
  6. #构造函数,类被初始化时调用
  7. def __init__(self,fileName="", filePath="", fileType=""):
  8. print("base init:",fileName,filePath, fileType)
  9. self.setFileName(fileName)
  10. self.setFilePath(filePath)
  11. self.setFileType(fileType)
  12. self.setFullPath()
  13. #设置文件名
  14. def setFileName(self, fileName):
  15. #判断 fileName的值 是不是字符串
  16. if not isinstance(fileName, str):
  17. raise Exception('fileName must be string.')
  18. self.__fileName = fileName
  19. #设置文件路径
  20. def setFilePath(self, filePath):
  21. if type(filePath) !=str:
  22. raise Exception('filePath must be string.')
  23. self.__filePath = filePath
  24. #设置文件完整的路径
  25. def setFullPath(self):
  26. #upload/docx/xx.docx
  27. #return self.__filePath+"/"+self.__fileName
  28. return "%s/%s"%(self.__filePath, self.__fileName)
  29. def setFileType(self, fileType):
  30. if fileType not in ('docx','xlsx','pptx','txt'):
  31. raise Exception('不支持的文件格式.')
  32. #使用字典形式来识别不同的文件格式,因为python中没有switch..case语句
  33. mimeTypes = {
  34. 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  35. 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  36. }
  37. self.__fileType = fileType
  38. self.__mimeType = mimeTypes[fileType]
  39. def downloadFile(self): #下载的方法,Blob形式
  40. directory = os.getcwd() #获取当前程序的工作路径
  41. mFilePath = directory.replace('\\','/')+"/"+self.__filePath
  42. #response = send_file(self.setFullPath(), mimetype=self.__mimeType,
  43. # attachment_filename= self.__fileName, as_attachment=True)
  44. response = make_response(send_from_directory(mFilePath,self.__fileName, as_attachment=True))
  45. return response
  46. #生成操作,只定义不实现,由各派生类自己完成
  47. def export(self, exportData):
  48. try:
  49. pass
  50. except :
  51. pass