struts2文件上传


目录:
struts2文件上传_第1张图片

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>
  <package name="fileUpload" namespace="/liu" extends="struts-default">
      <action name="upload" class="liu.chao.upload.Upload">
         <param name="savePath">/tempUpload</param>
         <result name="success">/success.jsp</result>
         <result name="input">/error.jsp</result>
      </action>
  </package>
</struts>

java 代码:
package liu.chao.upload;

import java.io.File;

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

import com.opensymphony.xwork2.ActionSupport;

public class Upload extends ActionSupport {

	/**
	 *  @author 007liuchao007
	 * 
	 * */
	private File upload;//临时存储的文件
	private String uploadFileName;//上传的文件名
	private String uploadContentType;//文件类型
	private String savePath;//保存目录通过struts动态设置目录
	
	
	
	
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	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;
	}





	@Override
	public String execute()throws Exception{
		
        String realPath=ServletActionContext.getServletContext().getRealPath(this.getSavePath());
		File saveFile=new File(realPath,uploadFileName);
		
		FileUtils.copyFile(upload, saveFile);
		
		System.out.println("realPath:"+realPath);//创建指定的目录
		System.out.println("upload.getName():"+upload.getName());//临时文件.tmp
		System.out.println("upload.toString:"+upload.toString());//临时文件.tmp
		System.out.println("uploadFileName:"+uploadFileName);//上传的文件名
		System.out.println("uploadContentType:"+uploadContentType);//上传的文件类型
		System.out.println("savePath:"+savePath);//通过struts.xml文件设置的目录:如:/tempUpload
		System.out.println("saveFile.toString:"+saveFile.toString());//保存文件的真实目录包括文件名字
		return SUCCESS;
	}
   
}

运行结果:
struts2文件上传_第2张图片

你可能感兴趣的:(java,struts)