Swagger如何配置以便可以成功下载Excel吗

发布于 2022-09-07 08:45:57 字数 948 浏览 9 评论 0

有人知道该如何配置Swagger支持下载Excel吗?

clipboard.png

为什么点击下载之后 文件打不开呢? 提示: can't be opened for some reason

代码: Flask + flasgger

    response = make_response(send_file(save_path))
    response.headers["Content-Disposition"] = "attachment; filename=download.xls;"
    return response

改成如下配置后 效果一样

    produces:
      - application/octet-stream
    parameters:
      - in: formData
        name: file
        type: file
        required: true
        description: Upload your excel file.
    responses:
      200:
        description: 处理后的文章下载
        schema:
          type: file

虽然页面上多了

clipboard.png

但是并未生效 还是一样

图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多彩岁月 2022-09-14 08:45:57

你应该把请求的Accept设置成application/octet-stream.
这其实有的奇怪, 因为一般情况下 Excel 文件的 Accept 是application/vnd.ms-excel.
但是由于 flasgger 是使用 swagger-ui 作为前端, 而 Swagger 发送文件类请求是使用 superagent, 使用的是 blob 技术, 需要设置 xhr 的 ResponseTypeblob.
我们看flasgger_static/lib/http.js:

if(this.binaryRequest(accept)) {
    r.on('request', function () {
      if(this.xhr) {
        this.xhr.responseType = 'blob';
      }
    });
  }
SuperagentHttpClient.prototype. binaryRequest = function (accept) {
  if(!accept) {
    return false;
  }
  return (/^image/i).test(accept)
    || (/^application\/pdf/).test(accept)
    || (/^application\/octet-stream/).test(accept);
};

只在 Accept 匹配为image/i,/^application\/pdf/,/^application\/octet-stream/, 才将 responseType 设置成 blob
所以要么将/^application\/vnd.ms-excel/这个匹配加入http.js, 要么将发送的请求全部设置成application/octet-stream.
也就是这样设置produces:
app.py:

@app.route('/excel')
def excel():
    """
    ---
    produces:
      application/octet-stream
    responses:
      200:
        description: description_text
        schema:
          type: file
    """
    save_path = 'demo.xls'
    response = make_response(send_file(save_path))
    response.headers['Content-Disposition'] = 'attachment; filename=demo.xls'
    return response

比如现在的目录结构:

clipboard.png
demo.py:

clipboard.png
apidocs页面:

clipboard.png

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文