如何 return 下载西里尔文文件名?

How to return downloaded file name in Cyrillic?

我想要 return 西里尔文名称的文件。

现在我的代码看起来像:

@GetMapping("/download/{fileId}")
    public void download(@PathVariable Long fileId, HttpServletResponse response) throws IOException {
        ...
        response.setContentType("txt/plain" + "; charset=" + "WINDOWS-1251");
        String filename = "русское_слово.txt";
        response.addHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
        //...
    }

当我从浏览器访问 url 时 - 浏览器为我提供了将文件保存在磁盘上的对话框,但它显示 _ 而不是西里尔符号。

看起来是响应头编码问题:

{
  "access-control-expose-headers": "Content-disposition",
  "content-disposition": "attachment; filename=???_??.txt",
  "date": "Fri, 28 Dec 2018 15:53:44 GMT",
  "transfer-encoding": "chunked",
  "content-type": "txt/plain;charset=WINDOWS-1251"
}

我尝试了以下选项:

response.addHeader("Content-disposition", "attachment; filename*=UTF-8''" + filename);

及以下:

response.addHeader("Content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename,"UTF-8"));

但没用

我该如何解决这个问题?

如果您使用 Spring 5+,您可以使用 ContentDisposition:

String filename = "русское слово.txt";

ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
    .filename(filename, StandardCharsets.UTF_8)
    .build();
System.out.println(contentDisposition.toString());

输出:

attachment; filename*=UTF-8''%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%BE%D0%B5%20%D1%81%D0%BB%D0%BE%D0%B2%D0%BE.txt

ContentDisposition 隐藏了您尝试做的所有工作(参见其 toString 实现):

if (this.filename != null) {
    if (this.charset == null || StandardCharsets.US_ASCII.equals(this.charset)) {
        sb.append("; filename=\"");
        sb.append(this.filename).append('\"');
    }
    else {
        sb.append("; filename*=");
        sb.append(encodeHeaderFieldParam(this.filename, this.charset));
    }
}

此外,如果您不想直接处理 HttpServletRequest,您可以 return ResponseEntity 代替:

@RequestMapping("/")
public ResponseEntity<Resource> download() {
  HttpHeaders httpHeaders = new HttpHeaders();
  String filename = "русское_слово.txt";

  ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
      .filename(filename, StandardCharsets.UTF_8)
      .build();
  httpHeaders.setContentDisposition(contentDisposition);

  return new ResponseEntity<>(new ByteArrayResource(new byte[0]),
      httpHeaders, HttpStatus.OK);
}