【发布时间】:2020-04-24 15:39:09
【问题描述】:
我正在开发一种允许上传和下载文件的个人云项目(具有类似谷歌的搜索功能)。后端是用 python 编写的(使用 aiohttp),而我使用 react.js 网站作为客户端。上传文件时,后端将其存储在文件系统中并使用其 sha256 哈希重命名。原始名称和一些其他元数据存储在它旁边(描述等)。当用户下载文件时,我使用 multipart 提供它,我希望用户使用原始名称而不是哈希来获取它,实际上my-cool-image.png 比a14e0414-b84c-4d7b-b0d4-49619b9edd8a 更用户友好。但我做不到(无论我尝试什么,下载文件都会用哈希调用)。
这是我的代码:
async def download(self, request):
if not request.username:
raise exceptions.Unauthorized("A valid token is needed")
data = await request.post()
hash = data["hash"]
file_path = storage.get_file(hash)
dotfile_path = storage.get_file("." + hash)
if not os.path.exists(file_path) or not os.path.exists(dotfile_path):
raise exceptions.NotFound("file <{}> does not exist".format(hash))
with open(dotfile_path) as dotfile:
dotfile_content = json.load(dotfile)
name = dotfile_content["name"]
headers = {
"Content-Type": "application/octet-stream; charset=binary",
"Content-Disposition": "attachment; filename*=UTF-8''{}".format(
urllib.parse.quote(name, safe="")
),
}
return web.Response(body=self._file_sender(file_path), headers=headers)
我想澄清一件事:有时我会收到一条警告(在客户端)说Resource interpreted as Document but transferred with MIME type application/octet-stream。我不知道文件的 MIME 类型,因为它们是由用户提供的,但我尝试使用 image/png(我使用存储在服务器上的 png 图像进行了测试)。该文件没有被下载(它显示在浏览器中,这不是我想要的)并且文件名仍然是它的哈希,所以它对我的问题没有帮助。
这是后端的全部源代码: https://git.io/nexmind-node 和前端: https://git.io/nexmind-client
编辑: 我收到了 Julien Castiaux 的第一个答案,所以我尝试实施它,即使它看起来更好,但它并没有解决我的问题(我仍然有完全相同的行为):
async def download(self, request):
if not request.username:
raise exceptions.Unauthorized("A valid token is needed")
data = await request.post()
hash = data["hash"]
file_path = storage.get_file(hash)
dotfile_path = storage.get_file("." + hash)
if not os.path.exists(file_path) or not os.path.exists(dotfile_path):
raise exceptions.NotFound("file <{}> does not exist".format(hash))
with open(dotfile_path) as dotfile:
dotfile_content = json.load(dotfile)
name = dotfile_content["name"]
response = web.StreamResponse()
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = "attachment; filename*=UTF-8''{}".format(
urllib.parse.quote(name, safe="") # replace with the filename
)
response.enable_chunked_encoding()
await response.prepare(request)
with open(file_path, 'rb') as fd: # replace with the path
for chunk in iter(lambda: fd.read(1024), b""):
await response.write(chunk)
await response.write_eof()
return response
【问题讨论】:
标签: python http request multipart aiohttp