struts2实现文件的上传(仅限单文件)和下载

一、程序运行效果图和所需要的jar包:

应用程序的目录结构图:

二、新建上传文件的Action

第一种方式(在com.etc.action包下新建UploadAction):

<strong>package com.etc.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;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
    
    private File image; //上传的文件
    private String imageFileName; //文件名称
    private String imageContentType; //文件类型

    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        //D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
System.out.println("realpath: "+realpath);
        
		if (image != null) {
            File savefile = new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            ActionContext.getContext().put("message", "文件上传成功");
            
        }else if(imageFileName!=null){//以下是用于测试上传文件是否成功 </strong>
<strong>        	imageFileName=new String(imageFileName.getBytes("iso-8859-1"),"gbk");
        	String path=ServletActionContext.getServletContext().getRealPath("/images/"+imageFileName);
        	
System.out.println(path+"您要下载的文件名:"+imageFileName);
        	
        }
        //为files赋值,目的:在message.jsp中列出/images文件下的所有文件
        this.getFiles(new File(realpath));
        
        return "success";
    }
    //列出文件夹下的所有文件
    File files[];
    
    public File[] getFiles() {
		return files;
	}
	public void setFiles(File[] files) {
		this.files = files;
	}
	public void getFiles(File dir){
    	files=dir.listFiles();
    	for(int i=0;i<files.length;i++){
System.out.println("文件夹下的文件"+files[i].getName());
    	}
    }
    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    
}</strong>

第二种方式(在com.etc.action包下新建UploadAction2):

<strong>package com.ljq.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

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

    // 封装上传文件域的属性
    private File image;
    // 封装上传文件类型的属性
    private String imageContentType;
    // 封装上传文件名的属性
    private String imageFileName;
    // 接受依赖注入的属性
    private String savePath;

    @Override
    public String execute() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 建立文件输出流
            System.out.println(getSavePath());
            fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());
            // 建立文件上传流
            fis = new FileInputStream(getImage());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("文件上传失败");
            e.printStackTrace();
        } finally {
            close(fos, fis);
        }
        return SUCCESS;
    }

    /**
     * 返回上传文件的保存位置
     * 
     * @return
     */
    public String getSavePath() throws Exception{
        return ServletActionContext.getServletContext().getRealPath(savePath); 
    }

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

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    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();
            }
        }
    }

}
</strong>

三、

Struts2.xml配置文件:

<strong><?xml version="1.0" encoding="gbk" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.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="gbk" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
    
         
    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="upload2" class="com.etc.action.UploadAction" >
            <result name="input">/upload.jsp</result>
            <result name="success">/message.jsp</result>
        </action>
    </package>
    
    <!-- 以下配置是文件下载的配置,参数中必须是fileName="${文件名变量}" 需要下载文件的时候可以把下面的代码注释去掉 -->
    <!--<package name="download" namespace="/download" extends="struts-default">
    	<action name="fileDownload" class="com.etc.action.FileDownloadAction">
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;fileName="${imageFileName}"</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
    -->    
</struts>    </strong>

四、上传表单页面【项目中webroot目录下的upload.jsp页面的内容】

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>文件上传</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>

    <body>
    	struts2实现单文件的上传和下载
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <form action="${pageContext.request.contextPath}/upload/upload2.do" 
              enctype="multipart/form-data" method="post">
            文件:<input type="file" name="image">
                <input type="submit" value="上传" />
        </form>
        <br/>
        <s:fielderror />
    </body>
</html></strong>

显示结果页面【项目中webroot目录下的message.jsp页面的内容】

<strong><%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>上传成功</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head> 
  
  <body>
    上传成功!
    <br/><br/>
    <!-- ${pageContext.request.contextPath} tomcat部署路径,
          如:D:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->
    <img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
    <s:debug></s:debug>
    <hr>
    显示出images文件夹下的所有文件
    <hr>
    <!-- 遍历UploadAction中的files,列出已经上传至images文件夹下的所有文件 -->
    <s:iterator value="files">
    	<a href="${pageContext.request.contextPath }/download/fileDownload.do?imageFileName=<s:property value="name"/>"><s:property value="name"/></a><br>
    </s:iterator>
  </body>
</html></strong>

 

五、新建下载文件的Action 参考此处代码来源:http://www.cnblogs.com/xiaoluo501395377/archive/2012/10/26/2740882.htmlhttp://blog.csdn.net/lk519186921/article/details/7050799此链接中介绍的更详细】

在com.etc.action包下新建FileDownloadAction【下载文件时,需要使用此Action类,此Action的配置,请见上面struts2.xml中的相应配置信息】

package com.etc.action;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileDownloadAction extends ActionSupport{
	//在此文件中要注意public InputStream getDownloadFile()的名称在Struts2配置文件配置,
	//返回的是一个InputStream类型的对象。
	
	private InputStream downloadFile;//文件下载的输入流,在struts.xml中有相应配置
	private String imageFileName; //文件名称
	

	/**
     * 对imageFileName参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK
     * 这里使用request.setCharacterEncoding解码无效.
     * 只有解码了,getDownloadFile()方法才能在下载目录下正确找到请求的文件
     */
	public void setImageFileName(String imageFileName) {//
		try {
			this.imageFileName = new String(imageFileName.getBytes("iso-8859-1"),"gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	/**
     * @getImageFileName 此方法对应的是struts.xml文件中的:
     *  <param name="contentDisposition">attachment;fileName="${imageFileName}"</param>
     * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对imageFileName再次编码
     * 否则中文名文件将出现乱码,或无法下载的情况
     */
	public String getImageFileName() {
		try {
			imageFileName=new String(imageFileName.getBytes(),"iso-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return imageFileName;
	}
	
	/**
     * @getDownloadFile 此方法对应的是struts.xml文件中的:
     *  <param name="inputName">downloadFile</param> 返回下载文件的流,可以参看struts2的源码
     * 只需设置输入流downFile的getter即可,不需设置setter
     */
    public InputStream getDownloadFile() {
    		System.out.println("要下载的文件的文件名称:"+imageFileName);
    		return ServletActionContext.getServletContext().getResourceAsStream("/images/"+imageFileName);
	}

	@Override
    public String execute() throws Exception {
        return SUCCESS;
    }

}


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 


<?xml version="1.0" encoding="gbk" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.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="gbk" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
    
         
    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="upload2" class="com.etc.action.UploadAction" >
            <result name="input">/upload.jsp</result>
            <result name="success">/message.jsp</result>
        </action>
    </package>
    
    <!-- 以下配置是文件下载的配置,参数中必须是fileName="${文件名变量}" -->
    <package name="download" namespace="/download" extends="struts-default">
    	<action name="fileDownload" class="com.etc.action.FileDownloadAction">
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;fileName="${imageFileName}"</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
    
</struts>    


 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值