响应二进制数据下载

问题描述 投票:0回答:1

我正在尝试从输入字段中输入文件,将其临时保存到磁盘,然后回复并重新下载相同的文件。

为了做到这一点,我读到我需要用content-type : application/octet-streamcontent-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}"')

这些是我的响应标题:Response headers

这是我的回复正文:Response body

但是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)
python pyramid
1个回答
0
投票

显然,我在想如何以错误的方式执行此操作。通过Response('OK')上传文件时,我需要返回一个/process,并再次请求返回一个FileResponse对象,构建另一个端点/download,然后返回该文件响应对象,从而解决了此问题。

© www.soinside.com 2019 - 2024. All rights reserved.