【问题标题】:Spring REST API: download file and choose the name and location to save [closed]Spring REST API:下载文件并选择保存的名称和位置[关闭]
【发布时间】:2021-07-05 22:48:58
【问题描述】:

我正在尝试立即下载生成的文件而不将它们保存在持久存储中。

@Operation(
      summary = "Download csv.",
      description = "Download csv.",
      responses = {@ApiResponse(content = @Content(
          mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE))}
  )
  @GetMapping(value = "/download", produces = APPLICATION_OCTET_STREAM_VALUE)
  public Resource downloadFile(HttpServletRequest request) {
    String s =
        "uuid1\tdata\n" +
        "uuid2\tdata\n" +
        "uuid3\tdata";
    ByteArrayResource resource = new ByteArrayResource(s.getBytes(), "description");
    return resource;
  }

因此,我通过 Swagger 获得了一个有效的下载链接,或者通过直接请求立即下载。

我想做的事:

  1. 要预先设置将下载的文件的名称和扩展名。
  2. 我想得到提示并选择保存位置。

可以只做后端吗?

【问题讨论】:

    标签: java spring download swagger spring-restcontroller


    【解决方案1】:

    To pre-set the name and extension for the file, that will be downloaded.

    尝试将HttpServletResponse 对象注入您的控制器方法并在该响应对象上设置标题,如下所示:

    response.setHeader("Content-Disposition", "attachment; filename=<yourfilename>.<yourextension>");

    如果您希望文件名是动态的或依赖于某些属性,可以随意格式化字符串。

    其他人必须回答你的第二点,因为我还没有遇到过。

    编辑:错字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2020-08-06
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多