1. 程式人生 > >Spring Boot專案實現下載專案根目錄下指定目錄(doc)裡的檔案

Spring Boot專案實現下載專案根目錄下指定目錄(doc)裡的檔案

1.頁面請求下載

<a href="/downloadFile">點選下載專案中的檔案</a>


2.controller接收頁面下載的請求,開始下載專案中的檔案,其中使用到了自定義的FileUtil類

		@RequestMapping("downloadFile")
		@ResponseBody
		public void Download(HttpServletResponse response) {
			String fileName = "ceshi1.txt";
			String result = FileUtil.downloadFile(response, fileName);
			System.out.println(result);

		} 
3.FileUtil.java工具類

   注意導包的時候,使用的是import org.springframework.util.ResourceUtils;

	/**
	 * 下載專案根目錄下doc下的檔案
	 * @param response response
	 * @param fileName 檔名
	 * @return 返回結果 成功或者檔案不存在
	 */
	public static String downloadFile(HttpServletResponse response, String fileName) {
		File path = null;
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;		
		try {
			path = new File(ResourceUtils.getURL("classpath:").getPath());
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(path + "/doc/" + fileName)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (FileNotFoundException e1) {
			//e1.getMessage()+"系統找不到指定的檔案";
			return "系統找不到指定的檔案";
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "success";
	}


4.專案根目錄下doc裡放置測試檔案ceshi1.txt


5、注意:如果將專案部署到linux下有可能回出現,下載檔案為空,或者出現下載檔案時,檔案出現亂碼,FileUtil.java解決方法如下

	/**
	 * 下載專案根目錄下doc下的檔案
	 * @param response response
	 * @param fileName 檔名
	 * @return 返回結果 成功或者檔案不存在
	 */
	public static String downloadFile(HttpServletResponse response, String fileName) {
		InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream("doc/" + fileName);
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		try {
			String name = java.net.URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLDecoder.decode(name, "ISO-8859-1") );
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;		
		try {
			os = response.getOutputStream();			
			bis = new BufferedInputStream(stream);
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (FileNotFoundException e1) {
			//e1.getMessage()+"系統找不到指定的檔案";
			return "系統找不到指定的檔案";
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "success";
	}

6、如果在linux下部署專案,在不同瀏覽器下載專案內檔案出現亂碼的情況,參照如下解決

     6.1、前臺傳遞引數頁面

<div class="cg-title">
	<span>數達營銷白皮書</span> 
	<a href=""> 
	   <img alt="" src="/static/img/icon/下載.png"> 點此下載
	</a>
</div>

    6. 2、javascript頁面
//  檔案下載demo
    $(".cg-title a").bind("click", function () {
        url = "/testDownFile?filename="+encodeURI($(this).prev().text());
        console.log(url)
        location.href = url;
        return false;
    })
    6.3、controller核心程式碼塊
	@RequestMapping("testDownFile")
	@ResponseBody
	public void Download(HttpServletRequest request, HttpServletResponse response) {
		String fileName = request.getParameter("filename")+".pdf";
		System.out.println(fileName);
		String result = FileUtil.downloadFile(response, fileName, request.getHeader("User-Agent").indexOf("Trident")==-1);
		System.out.println(result);

	}

   6.4、FileUtil.java
	/**
	 * 下載專案根目錄下doc下的檔案
	 * @param response response
	 * @param fileName 檔名
	 * @return 返回結果 成功或者檔案不存在
	 */
	public static String downloadFile(HttpServletResponse response, String fileName, boolean notIE) {
		InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream("doc/" + fileName);
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		try {
			String name = java.net.URLEncoder.encode(fileName, "UTF-8");
			if (notIE) {
				name = java.net.URLDecoder.decode(name, "ISO-8859-1");
			}
			response.setHeader("Content-Disposition", "attachment;filename=" + name );
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;		
		try {
			os = response.getOutputStream();			
			bis = new BufferedInputStream(stream);
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (FileNotFoundException e1) {
			//e1.getMessage()+"系統找不到指定的檔案";
			return "系統找不到指定的檔案";
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "success";
	}