1. 程式人生 > >Spring 實現檔案下載功能

Spring 實現檔案下載功能

方式1:

public void download(HttpServletResponse response,@RequestParam(value="params") String params) throws IOException, DocumentException{
		response.setContentType("application/pdf");
        //設定Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=pdf.pdf");
        
        //讀取檔案 生成一個位元組陣列
        byte[] a = ;
        OutputStream out = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(a);
        //寫檔案
        int b;
        while((b=in.read())!= -1)
        {
            out.write(b);
        }
        in.close();  
        out.close(); 
	}

Type是返回的檔案型別,而Content-Disposition則是告訴瀏覽器,本次返回的是一個附件,檔名是什麼。


方式二:spring對上述方法的封裝

@RequestMapping(value="/html2pdf",method=RequestMethod.POST)
	public ResponseEntity<byte[]> downloadFile(HttpServletResponse response,@RequestParam(value="params") String params) throws IOException, DocumentException{
		if(null !=params ){
			String html = params;
			String filename = "pdf.pdf";
			try {
				HttpHeaders headers = new HttpHeaders();  
		        //下載顯示的檔名,解決中文名稱亂碼問題  
		        String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
		        //通知瀏覽器以attachment(下載方式)開啟圖片
		       // headers.setContentDispositionFormData("attachment", downloadFielName);
		        headers.add("Content-Disposition", "attachment;filename=pdf.pdf");
		        headers.add("contentType", "application/pdf");
		        //application/octet-stream : 二進位制流資料(最常見的檔案下載)。
		        return new ResponseEntity<byte[]>(HTML2PDF.html2PDF(html),    
		                headers, HttpStatus.CREATED);
			} catch (Exception e) {
				return null;
			}


		}
		return null;
	}