1. 程式人生 > >七、Struts2之檔案上傳與下載

七、Struts2之檔案上傳與下載

 

一、Struts2檔案上傳

Struts2的檔案上傳實現非常簡單,只需要簡單幾步就可完成;

注意:

(1)檔案上傳的struts2標籤為:<s:file name="" label="上傳"/>

(2)檔案上傳的前提是表單屬性method="post" enctype="multipart/form-data";

(3)web應用中必須包含common-fileupload.jar和common-io.jar,因為struts2預設上傳解析器使用的是jakarta;

(4)可以在struts.xml中配置最大允許上傳的檔案大小:<constant name="struts.multipart.maxSize" value="....."/>,預設為2M;

1.普通檔案上傳

實現規則:

(1)在JSP中設定表單控制元件<s:file name="upload" label="上傳"/>

(2)在Action中定義屬性:

private File upload;        //包含檔案內容

private String uploadFileName;    //上傳檔案的名稱;

private String uploadContentType;    //上傳檔案的MIME型別;

這些屬性都會隨著檔案的上傳自動賦值;

(3)在execute()中完成寫入磁碟功能;

程式碼示例:

Upload01Action.java

package org.upload.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Upload01Action extends ActionSupport {
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	private String name;
	public String execute()throws Exception{
		String path = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
		String filename = path+File.separator+name;
		FileInputStream in = new FileInputStream(upload);
		FileOutputStream out = new FileOutputStream(filename);
		byte[]b = new byte[1024];
		int len = 0;
		while((len=in.read(b))>0){
			out.write(b,0,len);
		}
		out.close();
		return SUCCESS;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.custom.i18n.resources" value="message"></constant>
	<package name="default" namespace="/"  extends="struts-default">
		<action name="upload0*" class="org.upload.action.Upload0{1}Action">
			<param name="name">1.jpg</param>
			<result>/{1}.jsp</result>
		</action>
	</package>
</struts>


1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>My JSP '1.jsp' starting page</title>
  </head>
  
  <body> 
   	<s:form action="upload01" method="post" enctype="multipart/form-data">
   		<s:file name="upload" label="上傳"></s:file>
   		<s:submit value="上傳"></s:submit>
   	</s:form>
  </body>
</html>

2.利用攔截器進行過濾

手動實現過濾的方式非常簡單,就是利用輸入校驗的方式進行過濾,即在validate()中進行過濾;

而這裡要講的攔截器方式是很好的方式,只需要在配置檔案中配置,靈活性很好,能夠限制檔案的型別、檔案的大小;如果上傳的檔案不符合要求,則返回input邏輯檢視;

配置攔截器步驟:

(1)檔案上傳的攔截器為fileUpload;

(2)需要給定引數allowedTypes、maximumSize;

(3)在fileUpload攔截器後,需要新增<interceptor-ref name="defaultStack"/>

程式碼示例:

由於通過攔截器進行過濾只需要配置struts.xml,因此這裡只給出struts.xml的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.custom.i18n.resources" value="message"></constant>
	<package name="default" namespace="/"  extends="struts-default">
		<action name="upload0*" class="org.upload.action.Upload0{1}Action">
			<interceptor-ref name="fileUpload">
				<param name="allowedTypes">image/jpeg,image/gif</param>
				<param name="maximumSize">1024*1024</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<param name="name">1.jpg</param>
			<result>/{1}.jsp</result>
			<result name="input">/{1}.jsp</result>
		</action>
	</package>
</struts>

我們還需要配置檔案上傳失敗後的錯誤提示資訊,我們需要在全域性國際化資源檔案中配置:

struts.messages.error.content.type.not.allowed=檔案型別不匹配

struts.messages.error.file.too.large=檔案太大

二、Struts2檔案下載

我們在學習Servlet和HTTP協議時已經可以實現檔案下載,即寫content-disposition頭即可,struts2的實現原理也是這個,但是提供了更好的封裝性;

struts2的stream結果型別專門用於實現檔案下載;

(1)struts.xml中配置stream結果型別,並配置contentType、contentDisposition、bufferSize引數即可,模板:

<action name="download" class="">
	<result type="stream" name="success">
		<param name="contentType"></param>
		<param name="contentDisposition">attachment;filename=""</param>
		<param name="bufferSize">4096</param>
	</result>
</action>


(2)在Action中建立public InputStream getInputStream()throws Exception;方法,此方法用於獲得下載檔案的輸入流;

DownloadAction.java

package org.download.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {
	public InputStream getInputStream()throws Exception{
		
		return ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/upload/1.jpg");
		
	}
	public String execute()throws Exception{
		return SUCCESS;
	}
}


struts.xml

<action name="download" class="org.download.action.DownloadAction">
			<result type="stream" name="success">
				<param name="contentType">image/jpeg</param>
				<param name="contentDisposition">attachment;filename="1.jpg"</param>
				<param name="bufferSize">4096</param>
			</result>
		</action>

就可以完成下載;