1. 程式人生 > >java檔案下載以及中文亂碼解決

java檔案下載以及中文亂碼解決

  在客戶端下載檔案時替換下載檔案的名稱,但是當名稱是中文時瀏覽器會出現亂碼,解決程式碼如下:

    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;
}