- async def save_file(request, file):
- t = datetime.datetime.now()
- filepath = os.path.join(UPLOAD_PATH,
- t.strftime('%Y%m%d'))
- if not os.path.isdir(filepath):
- os.mkdir(filepath)
- ori_filepath = os.path.join(UPLOAD_PATH_ORIGINAL,
- t.strftime('%Y%m%d'))
- if not os.path.isdir(ori_filepath):
- os.mkdir(ori_filepath)
- timestamp = t.strftime("%H%M%S%f.")
- filename = os.path.join(filepath, timestamp)
- with open(filename + 'tmp', 'wb+') as f:
- ###必须转过来
- f.write(file.body)
- ###此处传二进制
- #f.write(file)
- mimetype = magic.from_file(filename + 'tmp', mime=True)
- suffix = allow_mime_type.get(mimetype)
- if not suffix:
- os.remove(filename + 'tmp')
- return 1, json({"status": 3, "data": "不允许的文件类型。"})
- if suffix in ("png", "jpg", "webp"):
- shutil.copyfile(filename + 'tmp', os.path.join(
- ori_filepath,
- timestamp + suffix),
- )
- shutil.copyfile(filename + 'tmp', filename + suffix)
- else:
- os.rename(filename + 'tmp', filename + suffix)
- url = UPLOAD_PATH+os.path.join(t.strftime('%Y%m%d'), t.strftime("%H%M%S%f." + suffix))
- image = {"image_url": url, "mime_type": mimetype}
- # await create_item(app.pool, "information", image)
- return url
Python上传文件代码
最新推荐文章于 2024-08-08 21:12:28 发布