1. 程式人生 > >Struts2 檔案上傳和下載

Struts2 檔案上傳和下載

一、 檔案上傳

Struts2檔案上傳時,要使用Struts的標籤<s:file />

例如:(以下的程式碼是一個小專案中的一部分,只給出檔案上傳下載部分程式碼,瞭解思想即可)

檔案上傳檢視:

<s:form namespace="/" action="ClassesAction_upload" enctype="multipart/form-data">
	<s:hidden name="classId" value="%{classId}"></s:hidden>
	<table width="88%" border="0" class="emp_table" style="width:80%;">
	  <tr>
	    <td>選擇課表:</td>
	    <td>&nbsp;</td>
	    <td>&nbsp;</td>
	  </tr>
	  <tr>
	    <td colspan="3">
	    <s:file name="schedule" ></s:file>
	    </td>
	  </tr>
	</table>
</s:form>
  • 表單中的檔案格式型別enctype,要設定成"multipart/form-data"
  • 檔案上傳的標籤<s:file name=""/>

實現部分:

	@InputConfig(resultName="uploadInput")
	public String upload() throws IOException{
		//1. 獲得存放檔案的目錄
		String parentDir = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
		//2. 隨機名稱
		String fileName = UUID.randomUUID().toString().replace("-", "")+scheduleFileName;
		//3. 儲存檔案
		FileUtils.copyFile(schedule, new File(parentDir,fileName));
		
                //將資料儲存在資料庫classes表中
		classes.setUploadFilename(scheduleFileName);
		classes.setUploadTime(new Date());
		classes.setUploadPath("/WEB-INF/upload/"+fileName);
		//4. 更新
		this.classesService.updateUpload(classes);
		
		return "upload";
	}

二、 檔案下載

實現程式碼(action)

	//寫入流(要有get/set方法)
        private InputStream inputStream;
        //檔名(也要寫get/set方法)
	private String filename;

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public InputStream getInputStream() {
		return inputStream;
	}
	
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public String getFilename() {
		return filename;
	}

	
	public String download() throws Exception{
		CrmClasses downloadClasses = this.classesService.findById(classes);
		filename = downloadClasses.getUploadFilename();
		String filePath = downloadClasses.getUploadPath();
		if(filename==null){
			return "uploadInput";
		}
		String userAgent = ServletActionContext.getRequest().getHeader("user-agent").toLowerCase();
		if(userAgent.contains("mise")||userAgent.contains("like gecko")){
			filename = URLEncoder.encode(filename,"utf-8");//將不安全的檔名改為utf-8  IE
		}else{
			filename = new String(filename.getBytes("utf-8"),"iso8859-1");  //非IE
		}
		String realpath = ServletActionContext.getServletContext().getRealPath(filePath);
		inputStream = new FileInputStream(realpath);
		return "success";
	}

在Struts.xml檔案中設定檢視

			<result type="stream">
				<param name="contentType">application/octet-stream</param>
				<param name="inputName">inputStream</param>
				<param name="contentDisposition">attachment;filename=${filename}</param>
			</result>
  • contentType : 檔案的下載型別,通常情況下,設定為“application/octet-stream”即可,如果想設定成其他值可以參考:http://tool.oschina.net/commons
  • inputName : 得到action中檔案輸入流
  • contentDisposition : 得到下載的檔案的名稱