如何使用REST服务上传非ASCII文件名的文件?

时间:2014-02-16 08:22:45

标签: java html5 spring rest iframe

我使用Spring,Apache CXF创建Java 7 REST服务。

public SuccessfulResponse uploadFile(@Multipart("report") Attachment attachment)

我使用“Content-Disposition”参数来检索文件名。我已经阅读了一些用于下载文件的解决方案(例如,url-encoding)。但是如何处理非ASCII文件名进行上传?它是客户端还是服务器端解决方案?可以更改上述方法的签名。客户端使用html5文件api + iframe。

2 个答案:

答案 0 :(得分:1)

我的经验是内容处理一般不会处理UTF8。您可以简单地为文件名添加另一个多部分字段 - 多部分字段支持字符集指示,并在正确完成时处理UTF8字符。

答案 1 :(得分:0)

您可以使用UTF8作为文件名(根据https://tools.ietf.org/html/rfc6266https://tools.ietf.org/html/rfc5987)。对于Spring,最简单的方法是使用org.springframework.http.ContentDisposition类。例如:

ContentDisposition disposition = ContentDisposition
    .builder("attachment")
    .filename("репорт.export", StandardCharsets.UTF_8)
    .build();
return ResponseEntity
    .ok()
    .contentType(MediaType.APPLICATION_OCTET_STREAM)
    .header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
    .body((out) -> messageService.exportMessages(out));

这是从服务器发送文件(下载)的示例。要上传文件,您可以遵循相同的RFC,即使Content-Disposition标头也必须在浏览器上通过JavaScript进行准备,例如:

Content-Disposition: attachment;
                      filename="EURO rates";
                      filename*=utf-8''%e2%82%ac%20rates

在这种情况下,参数filename是可选的,并且是不支持RFC 6266(包含ASCII文件名)的系统的后备。 filename*的值必须是已编码的URL(https://www.url-encode-decode.com)。

相关问题