Struts2實現文件下載(使用註解的方式)

Struts2對文件的下載做了很優雅的處理,配置起來很簡單,使用也很方便。


下載流程概覽:

 

HttpRequest  --->   "downLoad--->  SUCCESS Result -->   輸出流


	//實現文件下載
	
	 private String fileName;  
	  
	 private String mimeType;  
	  
	 private InputStream inStream;  
	 
	 
	 
	public InputStream getInStream() {
		return inStream;
	}
	public void setInStream(InputStream inStream) {
		this.inStream = inStream;
	}
	public String getFileName() {
		 try {
			return new String(fileName.getBytes(),"ISO8859-1");
		} catch (UnsupportedEncodingException e) {
		    return this.fileName;  
		}  
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getMimeType() {
		return mimeType;
	}
	/***
	 * 實現文件下載
	 * @param  
	 * @return SUCCESS
	 * @throws DaoException
	 */
	@Action(value="/dbbak/downLoad",
			results={
			@Result(name="SUCCESS",params={  
		            "contentType", "${mimeType}", "inputName",  
		            "inStream", "contentDisposition", "attachment;filename=\"${fileName}\"",   
		            "bufferSize", "4096" },type="stream")
	})
	public String downLoad()throws DaoException{
		//獲取目錄下的前五個dmp文件名
		String path = HwUtils.getRequest().getRealPath("/") + "dbbak";
		
		mimeType = HwUtils.getServletContext().getMimeType(getFileName());	
		System.out.println(mimeType);
		inStream = HwUtils.getServletContext().getResourceAsStream("/dbbak/" + fileName);
		 if (inStream == null) {  
	            inStream = new ByteArrayInputStream("Sorry,File not found !".getBytes());  
	        } 
		
		return SUCCESS;
	}

這裏解釋一下,返回stream類型需要配置的參數


contentType  //可以有servletContext 獲得


inputstream  //這裏對應的是我們聲明的inputStream的名字


contentDisposition //是下載文件的描述,主要用於賦值下載文件的名字


bufferSize  //是緩衝區的字節數



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章