很多時候,為了方便,下載文件其實就直接寫了一個文件在服務器上面的路徑,然后直接點擊一個這個地址,瀏覽器就自然而然的開始下載了。
但是這次項目需要在文件下載之前修改文件的名字,也就是說,服務器上文件的名字和下載到本地文件的名字是不一樣的。
而在springMVC中怎么實現呢?
下面就是代碼部分
/** * 下載文件 * @author xx * */ @Controller @RequestMapping("downloadFile") @Scope(value="prototype") public class DownloadController { /** * 下載文件 * @param path 下載文件的路徑 * @param name 下載文件的名字,需要包含后綴名 * @return 下載文件的字節數組 */ @RequestMapping("download") public ResponseEntity<byte[]> download(String path,String name, HttpServletRequest request){ //設置http協議頭部 HttpHeaders headers = new HttpHeaders(); //設置文件名 String fileName = ""; try { fileName = new String(name.getBytes("UTF-8"),"iso-8859-1");//為了解決中文名稱亂碼問題 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //頭部設置文件類型 headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //獲取文件路徑 String targetDirectory = request.getServletContext().getRealPath("/") + path; File file=new File(targetDirectory); //返回文件字節數組 try { return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED); } catch (IOException e) { e.printStackTrace(); return null; } } }
前端用get或者post均可,可以根據自己的情況來,還有需要修改的是,代碼中獲取文件路徑的地方,有的項目是有文件服務器的,所以這個地方不能這么寫,還有的項目數據庫保存的可能路徑不一樣,反正需要根據自己的實際情況來修改,如果文件不存在就會報錯的。
window.location.href = "/downloadFile/download?path=" + imgURL + "&name=" + documentName + "." + documentType;
需要注意的是,需要判斷文件在服務器上面是否存在,在代碼中我沒寫實現,但是實際情況需要判斷的。