【问题标题】:Response binary data to download响应二进制数据下载
【发布时间】: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)

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

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

    例子:

    @view_config(route_name='process')
    def process_file(request):
        input_file = request.POST['file'].file
        db = request.POST['volume']
        input_file.seek(0)
        filename = '%s.mp3' % uuid.uuid4()
        file_path = os.path.join('/tmp', filename)
        with open(file_path, 'wb') as output_file:
            shutil.copyfileobj(input_file, output_file)
        if boost_track(file_path, filename, db):
            return Response(json_body={'filename': filename})
    
    @view_config(route_name='download')
    def download_file(request):
        filename = request.GET['filename']
        file_path = os.path.join('/tmp', filename)
        f = open(file_path, 'rb')
        return Response(body_file=f, charset='UTF-8', content_type='application/download', content_disposition=f'attachment; filename="{filename}"')
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 1970-01-01
      • 2021-08-10
      • 2015-11-15
      • 2016-07-03
      • 2021-06-10
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多