1. 程式人生 > >java web 基於IO流的檔案下載示例

java web 基於IO流的檔案下載示例

下載檔案有時候直接就是一個a連結,連結檔案地址,很ok,很簡單,但是這樣有些弊病,比如說,我要是想統計檔案下載數量呢,再加上,檔案並不是都放在伺服器目錄下,也有可能是別的目錄,再或者,像 .txt 的直接a連結就打開了。所以使用程式來下載也是很有必要的。

show code

直接上程式碼吧

@RequestMapping("/downloadFile")
	public void getFile(String name, HttpServletRequest request , HttpServletResponse response) {
		try {
			System.out.println( name );
			
			File file = new File(name);
			InputStream is = new BufferedInputStream( new FileInputStream(file) );
			OutputStream os = new BufferedOutputStream( response.getOutputStream() );
			
			response.setCharacterEncoding("utf-8");
			// 設定返回型別
		    response.setContentType("multipart/form-data");
		    // 檔名轉碼一下,不然會出現中文亂碼
		    response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("--chenparty下載站--" + file.getName(),"UTF-8"));
		    // 設定返回的檔案的大小
		    response.setContentLength((int)file.length());
		    
		    byte [] b = new byte[1024];
		    int len = 0;
		    
		    while(-1 != (len = is.read(b))) {
		    	os.write(b, 0, len);
		    }
		    os.flush();
		    
		    os.close();
		    is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}