Python上传文件代码

  1. async def save_file(request, file):
  2. t = datetime.datetime.now()
  3. filepath = os.path.join(UPLOAD_PATH,
  4. t.strftime('%Y%m%d'))
  5. if not os.path.isdir(filepath):
  6. os.mkdir(filepath)
  7. ori_filepath = os.path.join(UPLOAD_PATH_ORIGINAL,
  8. t.strftime('%Y%m%d'))
  9. if not os.path.isdir(ori_filepath):
  10. os.mkdir(ori_filepath)
  11. timestamp = t.strftime("%H%M%S%f.")
  12. filename = os.path.join(filepath, timestamp)
  13. with open(filename + 'tmp', 'wb+') as f:
  14. ###必须转过来
  15. f.write(file.body)
  16. ###此处传二进制
  17. #f.write(file)
  18. mimetype = magic.from_file(filename + 'tmp', mime=True)
  19. suffix = allow_mime_type.get(mimetype)
  20. if not suffix:
  21. os.remove(filename + 'tmp')
  22. return 1, json({"status": 3, "data": "不允许的文件类型。"})
  23. if suffix in ("png", "jpg", "webp"):
  24. shutil.copyfile(filename + 'tmp', os.path.join(
  25. ori_filepath,
  26. timestamp + suffix),
  27. )
  28. shutil.copyfile(filename + 'tmp', filename + suffix)
  29. else:
  30. os.rename(filename + 'tmp', filename + suffix)
  31. url = UPLOAD_PATH+os.path.join(t.strftime('%Y%m%d'), t.strftime("%H%M%S%f." + suffix))
  32. image = {"image_url": url, "mime_type": mimetype}
  33. # await create_item(app.pool, "information", image)
  34. return url
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值