【发布时间】: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