【发布时间】:2020-07-31 06:41:19
【问题描述】:
我正在尝试从输入字段输入文件,将其临时保存到磁盘并回复回复以重新下载相同的文件。
为了做到这一点,我读到我需要用content-type : application/octet-stream 和content-disposition: attachment; "filename=myfile.extension" 回复浏览器。
我可以在 /tmp 文件夹中存储和收听我的音乐文件,因此我知道它的输入部分可以正常工作。
这是我在 Pyramid 中的代码:
@view_config(route_name='process')
def process_file(request):
input_file = request.POST['file'].file
input_file.seek(0)
file_path = os.path.join('/tmp', '%s.mp3' % uuid.uuid4())
with open(file_path, 'wb') as output_file:
shutil.copyfileobj(input_file, output_file)
print(f"Wrote: {file_path}")
filename = file_path.split('/')[-1]
print(filename)
f = open(file_path, 'rb')
return Response(body_file=f, charset='UTF-8', content_type='application/octet-stream', content_disposition=f'attachment; "filename={filename}"')
但是 Chrome/Firefox 不会开始下载我的二进制文件。我做错了什么?
更新
我也尝试使用 Pyramid 中的FileResponse 没有成功,我仍然没有得到下载弹出窗口。
@view_config(route_name='process')
def process_file(request):
input_file = request.POST['file'].file
input_file.seek(0)
file_path = os.path.join('/tmp', '%s.mp3' % uuid.uuid4())
with open(file_path, 'wb') as output_file:
shutil.copyfileobj(input_file, output_file)
print(f"Wrote: {file_path}")
return FileResponse(file_path, request=request)
【问题讨论】: