我有一个接收 MultipartFile 的端点。
Resource upload(@PathVariable Integer id, @RequestParam MultipartFile file) throws IOException {
此文件通常是 .csv
,我需要处理每一行并保存数据。
但最近用户发送了一个使用 UTF-16 LE
编码的文件,这在数据中添加了很多奇怪的字符。
我希望接收具有任何编码的文件,并在处理文件之前始终强制使用我可接受的编码,例如 UTF-8
。
我该怎么做?
最佳答案
经过一些测试和搜索,我找到了解决方案。
要更改文件的字符集编码,我需要读取和写入应用新目标字符集的文件,但要创建可以接收任何字符集的通用文件,我需要识别源字符集。
为了实现这一点,我添加了一个名为 UniversalDetector
的依赖项:
<dependency>
<groupId>com.github.albfernandez</groupId>
<artifactId>juniversalchardet</artifactId>
<version>2.3.1</version>
</dependency>
使用它我可以做到这一点:
encoding = UniversalDetector.detectCharset(file.getInputStream());
if (encoding == null) {
//throw exception
}
以及转换文件的方法:
private static void encodeFileInLatinAlphabet(InputStream source, String fromEncoding, File target) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(source, fromEncoding));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target),
StandardCharsets.ISO_8859_1))) {
char[] buffer = new char[16384];
int read;
while ((read = reader.read(buffer)) != -1)
writer.write(buffer, 0, read);
}
}
这样我就可以接收任何字符集并以所需的字符集进行编码。
注意:就我而言,我始终需要 ISO_8859_1
中的文件,因此方法中的原因是固定的,但您可以接收目标字符集作为参数。
关于java - 在 Spring Boot 中更改上传的 MultipartFile 的编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60207446/