如何以西里尔文返回下载的文件名?

时间:2018-12-28 15:58:02

标签: java spring-mvc encoding download cyrillic

我想返回西里尔字母的文件。

现在我的代码如下:

@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"));

但没有帮助

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

如果您使用的是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,也可以返回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);
}