file.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, Body, File, UploadFile
  4. from fastapi.responses import FileResponse
  5. from starlette.responses import StreamingResponse
  6. from sqlalchemy.orm import Session
  7. from database import get_db
  8. import requests
  9. import json
  10. import os
  11. import base64
  12. import uuid
  13. import time
  14. from config import settings
  15. from pprint import pprint
  16. from exceptions import *
  17. from utils import *
  18. from extensions import logger
  19. import os
  20. from models import *
  21. from utils import *
  22. from utils.sg_auth import *
  23. from utils.StripTagsHTMLParser import *
  24. from PIL import Image
  25. from io import BytesIO
  26. router = APIRouter()
  27. FILE_ALIAS_MAP = {
  28. 'yyzz': '隐患点图片',
  29. 'yjya': '预案附件',
  30. 'ylzj': '演练总结',
  31. }
  32. @router.post('/upload')
  33. async def upload(
  34. *,
  35. request: Request,
  36. uuid: str = Body(...),
  37. fileType: str = Body(...),
  38. file: UploadFile = File(...),
  39. ext_info: str = Depends(yst_pass_ext),
  40. db: Session = Depends(get_db)
  41. ):
  42. sfzh = ext_info['cid']
  43. timestamp = int(time.time())
  44. file_name = file.filename
  45. logger.debug("fileupload {}", file_name)
  46. # 文件后续名校验
  47. suffix = os.path.splitext(file_name)[-1]
  48. if suffix.find('.') != -1:
  49. if suffix.lower() not in ['.jpg', '.jpeg', '.png', '.pdf']:
  50. return {
  51. 'fileName': '',
  52. 'basePath': ''
  53. }
  54. else:
  55. suffix = '.png'
  56. file_name = get_filename(suffix)
  57. file_dir = os.path.join('/data/upload/mergefile/uploads/', "{}/{}/{}".format("yst", uuid, fileType))
  58. os.makedirs(file_dir, mode=0o764, exist_ok=True)
  59. file_path = os.path.abspath("{}/{}".format(file_dir, file_name))
  60. if os.path.exists(file_path):
  61. os.remove(file_path)
  62. content = await file.read()
  63. with open(file_path, 'wb') as f:
  64. f.write(content)
  65. logger.debug("fileupload {}", file_path)
  66. file_desc = ''
  67. if fileType in FILE_ALIAS_MAP.keys():
  68. file_desc = FILE_ALIAS_MAP[fileType]
  69. db_entity = YssYstUploadFileEntity(uuid=uuid, sfzh=sfzh, file_name=file_name, save_filepath=file_path, file_type=fileType, file_desc=file_desc, created_time=timestamp)
  70. db.add(db_entity)
  71. db.commit()
  72. path = "{}/{}/{}".format(uuid, fileType, file_name)
  73. resp = {
  74. 'fileName': file_name,
  75. 'basePath': path
  76. }
  77. return yst_image_response(resp)
  78. def get_filename(suffix):
  79. return str(uuid.uuid1()) + suffix.lower()
  80. @router.post('/delete')
  81. def delete(
  82. *,
  83. request: Request,
  84. param: dict = Depends(yst_request_param),
  85. db: Session = Depends(get_db)
  86. ):
  87. path = get_req_param(param, 'path')
  88. file_path = os.path.abspath(os.path.join('/data/upload/mergefile/uploads/', "yst", path))
  89. if os.path.exists(file_path):
  90. print("delete file:", file_path)
  91. os.remove(file_path)
  92. db.query(YssYstUploadFileEntity).filter(YssYstUploadFileEntity.save_filepath == file_path).delete()
  93. db.commit()
  94. return yst_response({'ret':0})
  95. @router.post('/show')
  96. def show(
  97. *,
  98. request: Request,
  99. param: dict = Depends(yst_request_param),
  100. db: Session = Depends(get_db)
  101. ):
  102. uuid = get_req_param(param, 'uuid')
  103. valueList = []
  104. dir = os.path.join('/data/upload/mergefile/uploads/', "{}/{}".format("yst", uuid))
  105. print('upload dir', dir)
  106. if os.path.exists(dir):
  107. for file_type in os.listdir(dir):
  108. file_type_path = os.path.join(dir, file_type)
  109. if os.path.exists(file_type_path) and os.path.isdir(file_type_path):
  110. file_list = []
  111. for file_name in os.listdir(file_type_path):
  112. file_list.append("/mmh5_yjxm_yst/ebus/yst_mmsyjjzhyjxt/api/yst/file/show?thumb=1&file_name={}&rnd={}".format(file_name, unixstamp()))
  113. valueMap = {
  114. 'fileType': file_type,
  115. 'imageUrls': file_list
  116. }
  117. valueList.append(valueMap)
  118. sfz_list = []
  119. qtFile = []
  120. for n in valueList:
  121. file_type = n['fileType']
  122. if file_type in ['sfz_zm', 'sfz_bm']:
  123. sfz_list = sfz_list + n['imageUrls']
  124. else:
  125. qtFile.append({'fileName': FILE_ALIAS_MAP[file_type], 'imageUrls': n['imageUrls']})
  126. sfzFile = []
  127. if len(sfz_list) > 0:
  128. sfzFile = [{'fileName': '居民身份证', 'imageUrls': sfz_list}]
  129. return yst_response({
  130. 'sfzFile': sfzFile,
  131. 'qtFile': qtFile
  132. })
  133. @router.get('/show', response_class=FileResponse, summary="显示图片")
  134. async def show(
  135. *,
  136. request: Request,
  137. file_name: str,
  138. thumb: str = '',
  139. db: Session = Depends(get_db)
  140. ):
  141. row = db.query(YssYstUploadFileEntity).filter(YssYstUploadFileEntity.file_name == file_name).first()
  142. if row is not None:
  143. image_filepath = row.save_filepath
  144. print(image_filepath)
  145. if os.path.exists(image_filepath) == False:
  146. image_filepath = os.path.join(settings.UPLOAD_IMAGE_PATH, "blank.png")
  147. return FileResponse(image_filepath)
  148. suffix = os.path.splitext(file_name)[-1]
  149. print('file show ==========>', row.file_type, image_filepath, suffix)
  150. if thumb != '':
  151. print('thumb !!!')
  152. Image.MAX_IMAGE_PIXELS = None
  153. image = Image.open(image_filepath)
  154. buf = BytesIO()
  155. image.thumbnail((100, 100))
  156. image.save(buf, 'png')
  157. img_data = buf.getvalue()
  158. return StreamingResponse(BytesIO(img_data), media_type="image/png")
  159. else:
  160. return FileResponse(image_filepath)
  161. else:
  162. logger.error("file not exists {}", file_name)