簡體   English   中英

在 Spring Boot 中更改上傳的 MultipartFile 的編碼

[英]Change encoding of uploaded MultipartFile in Spring Boot

我有一個接收 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的文件,以便修復方法中的原因,但您可以接收目標字符集作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM