upload.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. crop = self.input('crop', 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 crop:
  47. #裁图类型,暂时居中裁图
  48. file_path = cropImage(file_path)
  49. self.out('yes', {'src':url + file_path.replace(Demeter.path + 'runtime', '')})
  50. def cropImage(file):
  51. img = Image.open(file)
  52. width = img.size[0]
  53. height = img.size[1]
  54. size = 0
  55. x = 0
  56. y = 0
  57. if width == height:
  58. return file
  59. elif width < height:
  60. size = width
  61. x = 0
  62. y = (height-width)/2
  63. else:
  64. size = height
  65. x = (width-height)/2
  66. y = 0
  67. #img.thumbnail((500, 500))
  68. crop = img.crop((x, y, size+x, size+y))
  69. file = file + '_crop_center.jpg'
  70. crop.save(file)
  71. return file