Struct2文件上传

开发步骤如下:

1、新建一个web工程,导入struts2上传文件所需jar,如下图

Struct2文件上传

目录结构

Struct2文件上传

1.jsp—uploadfile.jsp文件。

注意:form标签要使用Structs2的标签,如果使用HTML的form标签,则可能会出错,显示找不到action,原因不明。

(例如欢迎页面是index.jsp,从index跳转到uploadfile.jsp后再用HTML的form标签就会找不到对应的action

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>单文件上传</title>
</head>
<body>
	<s:form action="uploadfile1" method="post" namespace="/SingleUpload" enctype="multipart/form-data">
		<s:file name="upf" /> <s:submit value="方式1提交"/>
	</s:form>
	<br/>
	<s:form action="uploadfile2" method="post" namespace="/SingleUpload" enctype="multipart/form-data">
		<s:file name="upf" /> <s:submit value="方式2提交" />		
	</s:form>
</body>
</html>

  

2.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>
    <!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
        如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
    <constant name="struts.action.extension" value="do" />
    <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
    
         
    <!-- 文件上传action -->
    <package name="SingleUpload" extends="struts-default" namespace="/SingleUpload">
	<!-- 单文件上传,方法1 -->
	<action name="uploadfile1" class="com.oschina.upload.SingleUploadAction" method="execute1"  >
	    <!-- <param name="savePath">D:/FileUpLoad</param> -->
	    <result name="success">/success.jsp</result>  
	    <result name="error">/error.jsp</result>   
	</action>
	  
	<!-- 单文件上传,方法2 -->
	<action name="uploadfile2" class="com.oschina.upload.SingleUploadAction" method="execute2">
            <param name="savePath">D:/FileUpLoad</param>
	    <result name="success">/success.jsp</result>  
	    <result name="error">/error.jsp</result> 
	   
	    <!-- 配置过滤器 -->	    
            <interceptor-ref name="fileUpload">                
              <!-- <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param> --><!-- 文件过滤 -->                
               <param name="maximumSize">1025956</param><!-- 文件大小, 以字节为单位 -->
            </interceptor-ref>            
           <interceptor-ref name="defaultStack" /> <!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
      </action>
   </package>
</struts>

3、Action—SingleUploadAction.java

 package com.oschina.upload;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

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

@SuppressWarnings("serial")
public class SingleUploadAction extends ActionSupport{
    
    private File upf; //上传的文件
    private String upfFileName; //文件名称
    private String upfContentType; //文件类型
    private String savePath;  //设置的文件保存路径
    //第一种方式,使用FileUtils工具类复制文件。
    public String execute1()  {
    	System.out.print("come into excute1");
    	System.out.print("F://");
        if (upf != null) {
            File savefile = new File("d://FileUpLoad", upfFileName);
            if (!savefile.getParentFile().exists()){
            	savefile.mkdirs();
            }
                
            try {
				FileUtils.copyFile(upf, savefile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            ActionContext.getContext().put("upf-message", "使用方法1成功上传文件:"+upfFileName);
            return "success";
        }
        return "error";
    }
    //第二种方式,使用文件流读写存储
    public String execute2()  {
    	System.out.print("come into excute2");
    	System.out.println("文件的存储路径为:"+savePath);
    	FileOutputStream fos = null;
        FileInputStream fis = null;
        Boolean result = true;
        try {
        	// 建立文件上传流
            fis = new FileInputStream(upf);
        	// 建立文件输出流           
            fos = new FileOutputStream(getSavePath() + "\\" + upfFileName);            
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            ActionContext.getContext().put("upf-message", "使用方法2成功上传文件:"+upfFileName);
        } catch (Exception e) {
            result = false;
        	System.out.println("文件上传失败");
            e.printStackTrace();            
        } finally {
            close(fos, fis);
        }
        if (result) {
            return SUCCESS; 
	}else {
	    return "error";
	}
               
    }
    
    private void close(FileOutputStream fos, FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("FileInputStream关闭失败");
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("FileOutputStream关闭失败");
                e.printStackTrace();
            }
        }
    }

	public File getUpf() {
		return upf;
	}

	public void setUpf(File upf) {
		this.upf = upf;
	}

	public String getUpfFileName() {
		return upfFileName;
	}

	public void setUpfFileName(String upfFileName) {
		this.upfFileName = upfFileName;
	}

	public String getUpfContentType() {
		return upfContentType;
	}

	public void setUpfContentType(String upfContentType) {
		this.upfContentType = upfContentType;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

    
    
}

 

4显示结果页面—success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
    <base href="<%=basePath%>">    
    <title>请求成功</title>    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>	  
	<s:property value="upf-message" />
 </body>
</html>


你可能感兴趣的:(Struct2文件上传)