resttemplate上傳中文名文件亂碼問題


需要測試一個文件上傳的功能,選擇使用resttemplate,在網上百度了一下.

服務端是通過MultipartFile的getOriginalFileName獲取文件名的,如下:

public Result handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        ...
        final Path orginFile = Paths.get(file.getOriginalFilename());
        ...
    }

而這里中文文件名總是出現亂碼,嘗試了一些方法指定StringHttpMessageConverter的編碼為utf-8,沒用(猜測只能對form中文本字段生效,對文件無效,后來發現根源在於spring的FormHttpMessageConverter(spring 4.3.9),其中有這么一句:

private byte[] getAsciiBytes(String name) {
            try {
                return name.getBytes("US-ASCII");
            } catch (UnsupportedEncodingException var3) {
                throw new IllegalStateException(var3);
            }
        }

這里hardcoding了文件名編碼,而服務端是用utf-8編碼,故出現了文件名亂碼.

解決辦法:copy原FormHttpMessageConverter源碼,寫個新的類,將上述方法改為:

private byte[] getAsciiBytes(String name) {
            try {
                return name.getBytes("UTF-8");
            } catch (UnsupportedEncodingException var3) {
                throw new IllegalStateException(var3);
            }
        }

即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM