【问题标题】:Wrong encoding of file name with Spring MVC使用 Spring MVC 的文件名编码错误
【发布时间】:2019-11-20 14:00:45
【问题描述】:

我有一个 Spring MVC 处理程序方法,它返回文件 čšľ.csv,但文件名编码错误 - 我在 Chrome 中得到 ___.csv,在 Postman 中得到 ???.csv

代码可以看这里:

@SpringBootApplication
@Controller
public class EncodingsandboxApplication {

    public static void main(String[] args) {
        SpringApplication.run(EncodingsandboxApplication.class, args);
    }

    @RequestMapping(value = "/",
            produces = {"text/csv"},
            method = RequestMethod.GET)
    public ResponseEntity<Resource> getExample() {
        return ResponseEntity.ok()
                .contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
                .header("Content-Disposition", "attachment; filename=čšľ.csv")
                .build();
    }
}

我希望收到 Content-Disposition 标头为 attachment; filename=čšľ.csv 的响应,但我刚刚收到 attachment; filename=???.csv(使用 Postman)。

为什么会这样?如何获得正确编码的文件名?

我认为contentType(new MediaType("text", "plain", StandardCharsets.UTF_8)) 中的“UTF_8”可以解决问题,但它不会。我已经尝试过对文件名进行 url 编码(如下所示:"attachment; filename=" + URLEncoder.encode("čšľ.csv", StandardCharsets.UTF_8)),但我只是得到了文字 url 编码的文件名。

我还检查了spring.http.encoding.charset,但这里默认使用 UTF-8。

我的 Spring boot 版本是 2.2.0

【问题讨论】:

    标签: java spring http spring-mvc encoding


    【解决方案1】:

    您几乎是正确的,您忘记在filename 之后添加*

    @RequestMapping(value = "/", produces = {"text/csv"},  method = RequestMethod.GET)
    public ResponseEntity<Resource> getExample() throws Exception {
        return ResponseEntity.ok()
                .contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
                .header("Content-Disposition", "attachment; filename*=" + URLEncoder.encode("čšľ.csv", StandardCharsets.UTF_8.toString()))
                .build();
    }
    

    一些例子可以在RFC 5987找到

    【讨论】:

    • * 是具有额外字符集功能的“扩展”参数的后缀。
    【解决方案2】:

    您希望对文件名进行编码,以便在上传和下载文件时能够从文件名中找到相同的文件。 为此,您可以使用 URLEncoder 和 URLDecoder 类。

    String  fileName = URLEncoder.encode("čšľ.csv", "UTF-8");`
    

    【讨论】:

    • 我不明白 - 我没有上传任何东西。我只是从 Spring MVC 处理程序方法中请求一个文件。我已经尝试过 URLEncoder,如我的问题所示,但没有效果。
    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2017-07-01
    • 2017-12-25
    • 2020-03-23
    相关资源
    最近更新 更多