我正在尝试从输入字段中输入文件,将其临时保存到磁盘,然后回复并重新下载相同的文件。
为了做到这一点,我读到我需要用content-type : application/octet-stream
和content-disposition: attachment; "filename=myfile.extension"
回复浏览器。
我可以在/ tmp文件夹中存储和收听我的音乐文件,因此我知道它的输入部分有效。
这是我在金字塔中的代码:
@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无法开始下载我的二进制文件。我在做什么错?
UPDATE
我也尝试过使用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)
显然,我在想如何以错误的方式执行此操作。通过Response('OK')
上传文件时,我需要返回一个/process
,并再次请求返回一个FileResponse
对象,构建另一个端点/download
,然后返回该文件响应对象,从而解决了此问题。