upload.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter web page
  5. name:upload.py
  6. author:rabin
  7. """
  8. from __load__ import *
  9. from datetime import *
  10. import os
  11. import uuid
  12. from PIL import Image
  13. class index_path(Load):
  14. """
  15. @api {post} /upload 上传图片
  16. @apiVersion 1.0.0
  17. @apiName upload
  18. @apiGroup Common
  19. @apiParam {String} file 文件流名称
  20. @apiSuccess {Bool} status 状态
  21. @apiSuccess {String} msg 描述
  22. @apiSuccess {Number} code 状态码
  23. @apiSuccess {Object[]} data 返回数据
  24. @apiSuccess {String} data.src 图片地址
  25. @apiErrorExample 操作成功
  26. {"status": 1, "msg": "操作成功", "code": 0, "data": {"src":"url"}}
  27. @apiErrorExample 操作失败
  28. {"status": 2, "msg": "\u64cd\u4f5c\u5931\u8d25", "code": 0, "data": {}}
  29. """
  30. @auth
  31. @Web.setting
  32. def post(self, *args, **kwargs):
  33. url = self.request.protocol + "://" + self.request.host
  34. file_metas = self.request.files["file"]
  35. type = self.input('type', 1)
  36. # print(file_metas)
  37. day = str(date.today())
  38. day = day.split('-')
  39. for meta in file_metas:
  40. #meta['filename']
  41. file_name = str(uuid.uuid5(uuid.uuid1(), 'file'))
  42. file_path = day[0] + '/' + day[1] + '/' + day[2]
  43. file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','upload', file_path)) + '/' + Demeter.md5(file_name) + '.jpg'
  44. with open(file_path, 'wb') as up:
  45. up.write(meta['body'])
  46. if type:
  47. #裁图类型,暂时居中裁图
  48. file_path = self.crop(file_path)
  49. self.out('yes', {'src':url + file_path.replace(Demeter.path + 'runtime', '')})
  50. def crop(file):
  51. img = Image.open(file) #打开图片句柄
  52. width = img.size[0]
  53. height = img.size[1]
  54. size = 0
  55. if width < height:
  56. size = width
  57. else:
  58. size = height
  59. #img.thumbnail((500, 500))
  60. left = width/4
  61. crop = img.crop((left, 0, size+left, size))
  62. file = file + '_crop_center.jpg'
  63. crop.save(file)
  64. return file