struts2使用fileUpload拦截器实现文件上传

Struts2为文件上传提供了支持,借助于fileUpload拦截器,很容易实现文件上传。

index.jsp页面需注意enctype

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



  
  
  
  
      
Choose your file
success.jsp页面

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



  
  
  
  
      Upload file  succeed!
  
error.jsp页面

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



  
  
  
  
      Upload file failed!
  
这都是最简单的写法,只是实现功能而已。
Action类

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class UploadFile extends ActionSupport {

	/*
	 * 注意命名要与jsp文件中的name对应
	 * 假设jsp中,name为xx,那么拦截器可使用的三个参数,命名应为xx,xxFileName,xxContentType
	 */
	private File myFile;
	private String myFileFileName;
	private String myFileContentType;

	@Override
	public String execute() {
		// TODO Auto-generated method stub
		String finalPath = "E:/uploadFile";
		try {
			File finalFile = new File(finalPath, myFileFileName);
			FileUtils.copyFile(myFile, finalFile);
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}

	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 getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}

}

最后是struts.xml

  


	
	
	
    
    
	
		
		    
			
			    
				image/x-png,image/gif,image/pjpeg
				
				1025956
			
			
			
			/success.jsp
			/error.jsp
		
	

  

这样便可实现文件上传。



你可能感兴趣的:(struts2)