SpringCloud專案上傳檔案時中文檔名亂碼,檔案下載
阿新 • • 發佈:2018-12-26
一、檔案上傳亂碼
SpringCloud,路由zuul。
今天在做一個上傳檔案的功能,檔案傳到後臺getOriginalFilename()時檔名中文亂碼。
嘗試了以下2種辦法都不行:
- 對檔名重新編碼:fileName = new String(fileName.getBytes(“ISO-8859-1”),”utf-8”);
- 設定請求引數格式:request.setCharacterEncoding(“utf-8”);
wm-document:
path: /document/**
serviceId: wm-document
我剛開始嘗試在這個服務的請求連結前加上“/zuul”請求字首
wm-document:
path: /zuul/document/**
serviceId: wm-document
zuul:
servlet-path: /
原來的服務的連結不變。請求地址還是:http://localhost:8888/document/doc/upload
重新啟動服務,ok,檔名中文沒有亂碼了。
檔案上傳到指定伺服器路徑就通過 MultipartFile 的 transferTo轉存方法。
貼個單個檔案上傳的簡單方法:
/**
* 上傳單個檔案,不改變原檔名
*
* @param savePath
* @param file
* @return
* @throws IOException
*/
public static void uploadSingleFile(String savePath, MultipartFile file) throws IOException {
File dir = new File(savePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (file != null) {
File saveFile = new File(savePath + "/" + file.getOriginalFilename());
file.transferTo(saveFile);
}
}
二、檔案下載
配置檔案中配置的檔案上傳路徑和訪問路徑對映
部分配置檔案:
uploadPath: E:/upload/file/ ---上傳路徑
accessPath: /file/ ---訪問路徑對映
server:
port: 7111
tomcat:
basedir: E:/upload/temp
spring:
application:
name: wm-document
上傳的檔案都在E:/upload/file/這個目錄下。此模組服務名為wm-document,在zuul中配置的路徑為: /document/**
zuul:
servlet-path: /
routes:
wm-document:
path: /document/**
serviceId: wm-document
檔案下載路徑對映配置:
WebConfig.java
/**
* Author: RoronoaZoro丶WangRui
* Time: 2018/8/2/002
* Describe:
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
//下載檔案訪問路徑
@Value("${accessPath}")
private String fileUrl;
//上傳檔案路徑
@Value("${uploadPath}")
private String uploadPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//用fileUrl路徑對映uploadPath
registry.addResourceHandler(fileUrl + "**").addResourceLocations("file:/" + uploadPath);
super.addResourceHandlers(registry);
}
}
然後就可以直接訪問資料夾路徑下載檔案了。
譬如我在E:/upload/file/目錄下上傳了一個檔案 測試.docx
根據我的路徑配置,直接訪問:http://localhost:8888/document/file/測試.docx 就可以下載到檔案了。