|
|
@@ -0,0 +1,52 @@
|
|
|
+import logging
|
|
|
+import uuid
|
|
|
+
|
|
|
+from flask import request, Blueprint
|
|
|
+
|
|
|
+from config import UPLOAD_DIR
|
|
|
+from route.util import make_response
|
|
|
+
|
|
|
+from PIL import Image
|
|
|
+
|
|
|
+bp = Blueprint("upload", __name__, url_prefix='/')
|
|
|
+
|
|
|
+
|
|
|
+def upload(type):
|
|
|
+ # 检查是否正确上传了文件
|
|
|
+ if 'file' not in request.files:
|
|
|
+ return make_response(400, "no file part.", {}, 400)
|
|
|
+
|
|
|
+ file = request.files['file']
|
|
|
+ if file.filename == '':
|
|
|
+ return make_response(400, "no selected file.", {}, 400)
|
|
|
+
|
|
|
+ # 随机 uuid 名称
|
|
|
+ random_name = str(uuid.uuid4())
|
|
|
+
|
|
|
+ # 图片格式检查 & 转换
|
|
|
+ if type == "photo":
|
|
|
+ try:
|
|
|
+ img = Image.open(file.stream)
|
|
|
+ img.verify()
|
|
|
+ img = Image.open(file.stream)
|
|
|
+ img = img.convert("RGB")
|
|
|
+ img.save(open(UPLOAD_DIR + random_name + ".jpg", "wb"))
|
|
|
+ except Exception as e:
|
|
|
+ logging.exception(e)
|
|
|
+ return make_response(-1, "cannot identify image file.", {})
|
|
|
+ elif type == "video":
|
|
|
+ pass
|
|
|
+ else:
|
|
|
+ assert False, "未知上传格式"
|
|
|
+
|
|
|
+ return make_response(0, "success", {"uuid": random_name})
|
|
|
+
|
|
|
+
|
|
|
+@bp.route("/photos", methods=["POST"])
|
|
|
+def upload_photo():
|
|
|
+ return upload("photo")
|
|
|
+
|
|
|
+
|
|
|
+@bp.route("/videos", methods=["POST"])
|
|
|
+def upload_video():
|
|
|
+ return upload("video")
|