|
| 1 | +from flask import jsonify, request |
| 2 | +import os |
| 3 | +from lin.exception import Success, ParameterException, Failed |
| 4 | +from .oss import upload_image_bytes |
| 5 | +from .model import Image |
| 6 | +from .enums import LocalOrCloud |
| 7 | +from lin.db import db |
| 8 | +from lin.redprint import Redprint |
| 9 | +from lin.core import lin_config |
| 10 | + |
| 11 | +api = Redprint('oss') |
| 12 | + |
| 13 | + |
| 14 | +@api.route('/upload_to_local', methods=['POST']) |
| 15 | +def upload(): |
| 16 | + image = request.files.get('image', None) |
| 17 | + if not image: |
| 18 | + raise ParameterException(msg='没有找到图片') |
| 19 | + if image and allowed_file(image.filename): |
| 20 | + path = os.path.join(lin_config.get_config('oss.upload_folder'), image.filename) |
| 21 | + image.save(path) |
| 22 | + else: |
| 23 | + raise ParameterException(msg='图片类型不允许或图片key不合法') |
| 24 | + return Success() |
| 25 | + |
| 26 | + |
| 27 | +@api.route('/upload_to_ali', methods=['POST']) |
| 28 | +def upload_to_ali(): |
| 29 | + image = request.files.get('image', None) |
| 30 | + if not image: |
| 31 | + raise ParameterException(msg='没有找到图片') |
| 32 | + if image and allowed_file(image.filename): |
| 33 | + url = upload_image_bytes(image.filename, image) |
| 34 | + if url: |
| 35 | + res = { |
| 36 | + 'url': url |
| 37 | + } |
| 38 | + with db.auto_commit(): |
| 39 | + exist = Image.get(url=url) |
| 40 | + if not exist: |
| 41 | + data = { |
| 42 | + 'from': LocalOrCloud.CLOUD.value, |
| 43 | + 'url': url |
| 44 | + } |
| 45 | + one = Image.create(**data) |
| 46 | + db.session.flush() |
| 47 | + res['id'] = one.id |
| 48 | + else: |
| 49 | + res['id'] = exist.id |
| 50 | + return jsonify(res) |
| 51 | + return Failed(msg='上传图片失败,请检查图片路径') |
| 52 | + |
| 53 | + |
| 54 | +@api.route('/upload_multiple', methods=['POST']) |
| 55 | +def upload_multiple_to_ali(): |
| 56 | + imgs = [] |
| 57 | + for item in request.files: |
| 58 | + img = request.files.get(item, None) |
| 59 | + if not img: |
| 60 | + raise ParameterException(msg='没接收到图片,请检查图片路径') |
| 61 | + if img and allowed_file(img.filename): |
| 62 | + url = upload_image_bytes(img.filename, img) |
| 63 | + if url: |
| 64 | + # 每上传成功一次图片需记录到数据库 |
| 65 | + with db.auto_commit(): |
| 66 | + exist = Image.get(url=url) |
| 67 | + if not exist: |
| 68 | + data = { |
| 69 | + 'from': LocalOrCloud.CLOUD.value, |
| 70 | + 'url': url |
| 71 | + } |
| 72 | + res = Image.create(**data) |
| 73 | + db.session.flush() |
| 74 | + imgs.append({ |
| 75 | + 'key': item, |
| 76 | + 'url': url, |
| 77 | + 'id': res.id |
| 78 | + }) |
| 79 | + else: |
| 80 | + imgs.append({ |
| 81 | + 'key': item, |
| 82 | + 'url': url, |
| 83 | + 'id': exist.id |
| 84 | + }) |
| 85 | + return jsonify(imgs) |
| 86 | + |
| 87 | + |
| 88 | +def allowed_file(filename): |
| 89 | + return '.' in filename and \ |
| 90 | + filename.rsplit('.', 1)[1] in lin_config.get_config('oss.allowed_extensions', []) |
0 commit comments