1. Download the file class
Import javax.servlet.http.HttpServletResponse; Import java.io. * ; public class DownloadUtil { public boolean the FileDownload (HttpServletResponse the Response, String filePath, String fileName) throws UnsupportedEncodingException { File File = new new File (filePath); // create download true path object file, a parameter file iF (File.Exists ()) { // determines whether a file exists the response.setContentType ( "file application / vnd.ms-Excel; charset = UTF-. 8" ); response.setCharacterEncoding ( " . 8-UTF " ); response.setHeader ("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName,"UTF-8")); byte[] buffer = new byte[1024]; FileInputStream fis = null; //文件输入流 BufferedInputStream bis = null; OutputStream os = null; //输出流 try { os = response.getOutputStream(); fis = new FileInputStream(file); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while(i != -1){ os.write(buffer); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); return false; } try { bis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); return false; } } return true; }
2.
< A TH: the href = "@ {/ downloads / fileName} {} + $ + $ +} {filePath 'filePath =?'" > Download File </ A >
/** * 测试文件下载 * @param fileName * @param filePath * @param response * @return * @throws UnsupportedEncodingException */ @GetMapping("/download/{fileName}") public String testDownload(@PathVariable("fileName") String fileName,String filePath,HttpServletResponse response) throws UnsupportedEncodingException { System.out.println("==>开始文件下载!"); DownloadUtil downloadUtil = new DownloadUtil(); downloadUtil.fileDownload(response,filePath,fileName); return null; }