首页 > 代码库 > Struts学习二

Struts学习二

一,struts2实现单文件上传:

1>,  WEB-INF/lib下加入commons-fileupload-1.2.1.jarcommons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。

2>,  form表的enctype设置为:“multipart/form-data“,如下:

<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib uri="/struts-tags"   prefix="s"%>
<html>
  <head>
    <title>My JSP ‘index.jsp‘ starting page</title>
    </head>
  <body>
    <form action="${pageContext.request.contextPath}/upload/uploadAction_saveFile.action"  
          name="form1"  method="post"  enctype="multipart/form-data" >
             
             上传文件名称:<input type="file" name="uploadImage"><!--name名称要与Action中定义的字段对应-->
           <input type="submit" value="http://www.mamicode.com/上传">
    </form>
  </body>
</html>


3>,  Action类中添加以下属性,属性红色部分对应表单文件字段的名称:

private File uploadImage;  //得到上传的文件

private String uploadImageContentType;  //得到文件的类型

private String uploadImageFileName;  //得到文件的名称

代码:

import java.io.File;

import javax.servlet.ServletContext;

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

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
	
	//<input type="file" name="uploadImage">
	/*
	 * * 保存上传的文件,此时是一个临时文件,保存在如下的目录
	 *    E:\\apache-tomcat-6.0.18\\work\\Catalina\\localhost\\itcast0902struts2
	 *                \\upload__58d71e4b_1322cf0eaeb__7fff_00000000.tmp
	 *                
	 * * 当请求结束时,再删除该临时文件    
	 *    Removing file uploadImage E:\\apache-tomcat-6.0.18\work\Catalina\localhost\itcast0902struts2
	 *        \\upload__39b4493b_1322cfa9c5d__8000_00000000.tmp           
	 */
	private File uploadImage;
	
	//保存的是上传文件的类型 格式:htm上传表单的组件的name属性的值+ContentType
	private String uploadImageContentType;
	
	//保存上传文件的真实名称  格式:htm上传表单的组件的name属性的值+FileName
	private String uploadImageFileName;
	
	public String saveFile(){
		System.err.println("uploadImage  "+uploadImage);
		System.out.println("uploadImageContentType  "+uploadImageContentType);
		System.out.println("uploadImageFileName  "+uploadImageFileName);
		
		ServletContext sc=ServletActionContext.getServletContext();
		String realpath=sc.getRealPath("/pic");
		
		try {
			//保存上传的文件到指定的目录
			File file=new File(realpath,uploadImageFileName);
			FileUtils.copyFile(uploadImage, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	  return "success";	
    }

	public File getUploadImage() {
		return uploadImage;
	}

	public void setUploadImage(File uploadImage) {
		this.uploadImage = uploadImage;
	}

	public String getUploadImageContentType() {
		return uploadImageContentType;
	}

	public void setUploadImageContentType(String uploadImageContentType) {
		this.uploadImageContentType = uploadImageContentType;
	}

	public String getUploadImageFileName() {
		return uploadImageFileName;
	}

	public void setUploadImageFileName(String uploadImageFileName) {
		this.uploadImageFileName = uploadImageFileName;
	}
}


在struts.xml文件中配置:

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
	"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>  
  <!--修改上传文件大小的总开关,默认值是2M,对整个项目中的上传都有效  -->
  <constant name="struts.multipart.maxSize" value="http://www.mamicode.com/200097152"></constant>

  <package name="upload" namespace="/upload" extends="struts-default">
     <action name="uploadAction_*" class="cn.yujian.upload.UploadAction" method="{1}">
        <!-- 配置默认栈中上传拦截器的属性 -->
        <interceptor-ref name="defaultStack">
           <!-- 配置上传文件的大小,只对当前的action有效 -->
           <param name="fileUpload.maximumSize">3097152</param>
           <!-- 配置上传文件的类型,如果有多个类型,中间用,隔开 -->
           <param name="fileUpload.allowedTypes">text/plain,application/octet-stream</param>
           <!-- 配置上传文件的扩展名,如果有多个扩展名,中间用,隔开-->
           <param name="fileUpload.allowedExtensions">txt,xls</param>
        </interceptor-ref>
        <result name="success">/upload/success.jsp</result>
        <!-- 当上传失败时,要转下input所指向的页面 --> 
        <result name="input">/upload/error.jsp</result>
     </action>
  </package>
</struts>


二,struts2实现多文件上传:

1,form表单代码:

<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib uri="/struts-tags"   prefix="s"%>
<html>
  <head>
    <title>My JSP ‘index.jsp‘ starting page</title>
    </head>
  <body>
    <form action="${pageContext.request.contextPath}/upload/uploadsAction_saveFiles.action"  
          name="form1"  method="post"  enctype="multipart/form-data" >
             上传文件名称:<input type="file" name="uploadImages"><br>
             上传文件名称:<input type="file" name="uploadImages"><br>
             上传文件名称:<input type="file" name="uploadImages"><br>
                 
           <input type="submit" value="http://www.mamicode.com/上传">
    </form>
  </body>
</html>

2,Action代码:

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadsAction extends ActionSupport {

	private File[] uploadImages;

	private String[] uploadImagesContentType;

	private String[] uploadImagesFileName;

	public String saveFiles() {
		ServletContext sc=ServletActionContext.getServletContext();
		String realpath=sc.getRealPath("/pic");
		try {
			if(uploadImages!=null&&uploadImages.length>0){
				for(int i=0;i<uploadImages.length;i++){
					File file=new File(realpath,uploadImagesFileName[i]);
					FileUtils.copyFile(uploadImages[i], file);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}

	public File[] getUploadImages() {
		return uploadImages;
	}

	public void setUploadImages(File[] uploadImages) {
		this.uploadImages = uploadImages;
	}

	public String[] getUploadImagesContentType() {
		return uploadImagesContentType;
	}

	public void setUploadImagesContentType(String[] uploadImagesContentType) {
		this.uploadImagesContentType = uploadImagesContentType;
	}

	public String[] getUploadImagesFileName() {
		return uploadImagesFileName;
	}

	public void setUploadImagesFileName(String[] uploadImagesFileName) {
		this.uploadImagesFileName = uploadImagesFileName;
	}
}

3,struts.xml中配置:

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
	"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>  
  <!--修改上传文件大小的总开关,默认值是2M,对整个项目中的上传都有效  -->
  <constant name="struts.multipart.maxSize" value="http://www.mamicode.com/200097152"></constant>

  <package name="upload" namespace="/upload" extends="struts-default">
     <!-- 配置多文件上传 -->
     <action name="uploadsAction_*" class="cn.yujian.upload.UploadsAction" method="{1}">
        <result name="success">/upload/success.jsp</result>
        <result name="input">/upload/error.jsp</result>
     </action>
  </package>
</struts>


三,修改显示错误的资源文件的信息:

1>,  创建新的资源文件,例如fileupload.properties,放置在src

2> ,在资源文件中增加:

    struts.messages.error.uploading=上传错误: {0}

    struts.messages.error.file.extension.not.allowed=上传文件的扩展名不允许: {0} "{1}" "{2}" {3}

    struts.messages.error.file.too.large=上传文件太大: {0} "{1}" "{2}" {3}

    struts.messages.error.content.type.not.allowed=上传文件的类型不允许: {0} "{1}" "{2}" {3}

3>,在struts.xml文件中加载该资源文件:

  <!-- 配置加载国际化的资源文件, .properties不用加,如果有多个资源文件,用","隔开

        * cn.yujian.upload.fileupload:加载的是fileupload.properties资源文件

        * cn.yujian.i18n.resource:加载的resource系列的资源文件  

   -->

   <constant name="struts.custom.i18n.resources" 

             value="http://www.mamicode.com/cn.yujian.upload.fileupload>

   </constant>







Struts学习二