在客戶端下載文件時替換下載文件的名稱,但是當名稱是中文時瀏覽器會出現亂碼,解決代碼如下:
public org.springframework.http.ResponseEntity<InputStreamResource> handleExcel(HttpServletRequest request) throws Exception { String fileName = "模板下載.xsls"; //解決瀏覽器下載漢字亂碼的兼容問題 String userAgent = request.getHeader("User-Agent"); byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // 各瀏覽器基本都支持ISO編碼 String name = new String(bytes, "ISO-8859-1"); //網絡資源文件 //可以替換為網絡資源文件 //本地文件 PathResource file = new PathResource(FileUtil.getNewFileName(fileName)); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", "attachment;fileName=" + name); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); org.springframework.http.ResponseEntity<InputStreamResource> entity = org.springframework.http.ResponseEntity .ok() .headers(headers) .contentLength(file.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(file.getInputStream())); return entity; }