file.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import os
  2. import cv2
  3. from flask import request, jsonify, send_file
  4. from werkzeug.utils import secure_filename
  5. from werkzeug.datastructures import FileStorage
  6. import uuid
  7. from app import app
  8. from .resp import success_resp, error_resp
  9. import time
  10. from .req import is_empty
  11. UPLOAD_PATH = ""
  12. OUTPUT_DIR = ""
  13. class MimeTypes:
  14. png = "image/png"
  15. stream = "application/octet-stream"
  16. def get_upload_dir():
  17. return UPLOAD_PATH
  18. def get_output_dir():
  19. return OUTPUT_DIR
  20. def set_options(upload_path, save_dir):
  21. global UPLOAD_PATH, OUTPUT_DIR
  22. UPLOAD_PATH = upload_path
  23. OUTPUT_DIR = save_dir
  24. print("dirs", UPLOAD_PATH, OUTPUT_DIR)
  25. @app.route("/outputs/<path:filename>")
  26. def get_outputs_files(filename):
  27. # 处理后的文件
  28. download = is_empty(request.values.get('download')) is False
  29. mimetype = MimeTypes.stream if download else MimeTypes.png
  30. return send_file(os.path.join(OUTPUT_DIR, filename), mimetype=mimetype)
  31. @app.route("/uploads/<path:filename>")
  32. def get_upload_files(filename):
  33. # 用户上传的原始文件
  34. download = is_empty(request.values.get('download')) is False
  35. mimetype = MimeTypes.stream if download else MimeTypes.png
  36. return send_file(os.path.join(UPLOAD_PATH, filename), mimetype=mimetype)
  37. @app.route("/upload", methods=['POST'])
  38. def upload_file():
  39. # 上传图片
  40. if 'file' not in request.files:
  41. return jsonify(error_resp("请选择图片!"))
  42. file = request.files['file']
  43. file_md5 = request.form.get('fileMd5')
  44. file_path, file_id = save_upload_file(file, file_md5)
  45. img = cv2.imread(file_path)
  46. return jsonify(success_resp({
  47. "fileId": file_id,
  48. "url": file_url(file_path),
  49. "height": img.shape[0],
  50. "width": img.shape[1]
  51. }))
  52. @app.route("/download", methods = ['GET'])
  53. def download_file():
  54. file_id = request.values.get("fileId")
  55. file_path = get_file_id_path(file_id)
  56. if file_path is None:
  57. return "文件不存在", 404
  58. return send_file(file_path, mimetype="application/octet-stream", attachment_filename=file_id)
  59. def file_url(path, output=False):
  60. if output is True:
  61. file_id = os.path.relpath(path, OUTPUT_DIR)
  62. return "/outputs/{}".format(file_id)
  63. file_id = os.path.relpath(path, UPLOAD_PATH)
  64. return "/uploads/{}".format(file_id)
  65. def save_upload_file(file: FileStorage, md5 = None):
  66. # 如果区分用户,加文件前缀或者文件夹名称
  67. if file.filename == '':
  68. filename = "unknown.png"
  69. else:
  70. filename = secure_filename(file.filename)
  71. paths = os.path.splitext(filename)
  72. if md5 is not None and len(md5) > 0:
  73. filename = "{}_{}{}".format(paths[0], md5, paths[1])
  74. else:
  75. t = time.strftime("%Y%m%d%H%M%S", time.localtime())
  76. filename = "{}_{}_{}{}".format(paths[0], t, uuid.uuid4().hex, paths[1])
  77. file_path = get_upload_file_path(filename)
  78. if os.path.exists(file_path) is False:
  79. file.save(file_path)
  80. return file_path, filename
  81. def get_output_file_path(filename: str, suffix: str = None, fun: str = None):
  82. if filename == '':
  83. filename = "unknown.png"
  84. else:
  85. filename = secure_filename(filename)
  86. paths = os.path.splitext(filename)
  87. if suffix is None or len(suffix) == 0:
  88. suffix = time.strftime("%Y%m%d%H%M%S", time.localtime())
  89. if fun is not None:
  90. suffix = "{}_{}".format(fun, suffix)
  91. filename = "{}_{}{}".format(paths[0], suffix, paths[1])
  92. return os.path.join(OUTPUT_DIR, filename)
  93. def get_file_id(path, output=False):
  94. if output:
  95. file_id = os.path.relpath(path, OUTPUT_DIR)
  96. return "o_{}".format(file_id)
  97. file_id = os.path.relpath(path, UPLOAD_PATH)
  98. return file_id
  99. def get_file_id_path(filename: str):
  100. # 根据文件名称,获取文件的路径
  101. if str is None or len(filename) == 0:
  102. return None
  103. if filename.startswith("o_"):
  104. real_name = filename[2:]
  105. path = os.path.join(OUTPUT_DIR, real_name)
  106. if os.path.exists(path):
  107. return path
  108. path = os.path.join(UPLOAD_PATH, filename)
  109. if os.path.exists(path):
  110. return path
  111. return None
  112. def get_upload_file_path(name):
  113. return os.path.join(UPLOAD_PATH, name)