1. 程式人生 > >struts2多檔案上傳

struts2多檔案上傳

相比單檔案上傳,多檔案上傳只需要在private各種屬性的時候,定義成陣列

然後在上傳的時候使用迴圈來迴圈上傳

package com.rl.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;


/**
 * action動作類充當模型物件
 * @author renliang
 *
 */
public class UploadsAction extends ActionSupport{
	

	private String username;
	
	/**
	 * 要接收的檔案,命名需要和表單中的file型別的input的name一致
	 */
	private File[] upload;
	
	/**
	 * 檔名的接收 File屬性名FileName:固定寫法
	 */
	private String[] uploadFileName;
	
	/**
	 * 獲得上傳檔案的MIME型別,File屬性名字ContentType:固定寫法
	 */
	private String[] uploadContentType;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	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 upload() throws Exception{
		//獲得servletContext
		ServletContext sc = ServletActionContext.getServletContext();
		//獲得服務的絕對路徑
		
		for(int i = 0; i < upload.length; i++){
			String realPath = sc.getRealPath("/");
			realPath = realPath + "upload\\"+uploadFileName[i];
			//定義輸入輸出流
			FileUtils.copyFile(upload[i], new File(realPath));
		}
		return super.SUCCESS;
	}
	
}

在struts.xml中的配置

<!-- 多檔案上傳 -->
		<action name="renliangs" class="com.rl.action.UploadsAction" method="upload">
			<!-- 
				主動引用預設攔截器棧
			 -->
			<interceptor-ref name="defaultStack">
				<!-- 設定上傳攔截器fileUpload.allowedExtensions,  不要使用allowedExtensionsSet -->
				<param name="fileUpload.allowedExtensions">.png,.txt,jar</param>
			</interceptor-ref>
			<result name="success">/success.jsp</result>
			<result name="input">/form1.jsp</result>
		</action>