struts2文件上传.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

		<s:form action="uploadFile" method="post" enctype="multipart/form-data"  namespace="/FileUpload">
			<s:textfield name="username" label="username"></s:textfield>
			<s:password name="password" label="password" ></s:password>
			<s:file name="myfile" label="select file"></s:file>
			<s:submit></s:submit>
		</s:form>

<!--file:struts.xml-->

	<package name="uploadFileDemo" namespace="/FileUpload"
		extends="struts-default">
		<action name="uploadFile" class="test.action.UploadFile">
			<result>/FileUpload/upload-success.jsp</result>
			<result name="input">/FileUpload/upload.jsp</result>
			<interceptor-ref name="fileUpload">
				<param name="allowedExtensions">
					.jpg,.txt,.log
				</param>
				<!-- 
				<param name="allowedTypes">
					text/plain,application/jpeg
				</param>
 				-->
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</action>
	</package>


Action.java

package test.action;

import java.io.File;

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

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFile extends ActionSupport {

	@Override
	public String execute() throws Exception {
	
		System.out.println("UploadFile Action execute");
		//ServletActionContext.getRequest().getrea.getRealPath("/FileUpload");  //deprecated
		
		String pathRoot = ServletActionContext.getServletContext().getRealPath("/FileUpload");
		File file=new File(pathRoot,myfileFileName );
		FileUtils.copyFile(myfile,file);
		return SUCCESS;
	}

	private String username;
	private String password;
	private File myfile;

	private String myfileFileName;
	private String myfileContextType;
	
	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public File getMyfile() {
		return myfile;
	}

	public void setMyfile(File myfile) {
		this.myfile = myfile;
	}

	public String getMyfileFileName() {
		return myfileFileName;
	}

	public void setMyfileFileName(String myfileFileName) {
		this.myfileFileName = myfileFileName;
	}

	public String getMyfileContextType() {
		return myfileContextType;
	}

	public void setMyfileContextType(String myfileContextType) {
		this.myfileContextType = myfileContextType;
	}

}

posted @ 2010-12-05 21:00  庚武  Views(215)  Comments(0Edit  收藏  举报