如何从Falcon resp.stream获取.xlsx文件

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

我正在尝试从API获取生成的.xlsx文件。

我在后端有以下代码:

from io import BytesIO
from openpyxl import Workbook

@api_resource('/get_report')
class Report:
    @auth_required()
    def on_get(self, req, resp):
        wb = Workbook()
        ws = wb.active
        ws.title = "report"
        ws['C9'] = 'hello world'
        f = BytesIO()
        wb.save(f)
        f.seek(0)
        resp.stream = f
        resp.content_type = \
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

以及前端的以下代码:

ReportsAPI.getReport(filters).then(resp => {
 openXLS([resp.data], `report.xlsx`);
});

function openXLS(blob_data, filename) {
  let blob = new Blob(blob_data, {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  });
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  document.body.appendChild(link);
  link.style = "display: none";
  link.href = url;
  link.download = filename;
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}

我正在通过API请求下载文件,但文件已损坏。如果我将文件保存在后端的文件系统中(```wb.save('test.xlsx')`

), the file opens without problems.

I tried to save the file as indicated in the documentation for openpyxl, but it does not work. 

...
from tempfile import NamedTemporaryFile

wb = Workbook()
with NamedTemporaryFile() as tmp:
     wb.save(tmp.name)
     tmp.seek(0)
     resp.stream = BytesIO(tmp.read())

我究竟做错了什么?

在终端file -bi filename.xlsx上正常文件返回application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=binary,但在损坏的文件上它返回application/zip; charset=binary

我试图从终端向API发出请求

http  GET 'http://127.0.0.1:8000/api/v1/get_report' > test.xlsx

并且文件没有被破坏。似乎问题出在前端。

在我看来问题是编码,但我无法确定它。

python python-3.x file falcon
1个回答
0
投票

尝试为您的回复设置标题,如下所示:

def on_get(self, req, resp):
    wb = Workbook()
    ws = wb.active
    ws.title = "report"
    ws['C9'] = 'hello world'
    f = BytesIO()
    wb.save(f)
    f.seek(0)
    filename = 'sample.xlsx'
    resp.stream = f
    resp.content_type = \
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    resp.set_header("Content-Disposition", f"attachment; filename={filename}")

0
投票

问题出在我对api的请求中,我使用了axios,默认情况下它始终使用JSON处理数据。只需要将响应类型设置为arraybuffer

class ReportsAPI {
  getReport(filters) {
    return instance.get(`/get_report`, {
      params: { ...filters },
      responseType: "arraybuffer"
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.