`

struts2文件上传/下载(附源代码)

 
阅读更多

struts2对于文件的操作提供很多便捷的地方,因此在项目中多少会涉及到它的使用,当然网上关于它的帖子也确实不少,清楚地,不清楚的,详细的,不详细的,都有很多,我也曾学到过很多热爱分享的同行们的帮助,在这里,我便按我自己思路,整理了下,写成这篇博文,并提供效果图和附件的下载。

首先,按老规矩,上效果图:


图一


图二


图三


图四


图五


然后我们看下这个项目的结构图:



第一步,新建一个web项目,我这里偷了个懒,upload/download,干脆就叫updownload,并加入struts2的相关jar包

第二步,新建com.action.UploadAction.java代码如下:

package com.action;

import java.io.File;
import java.util.List;

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

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport
{
    private static final long serialVersionUID = 1L;
    
    private List<File>image;
    private List<String>imageContentType;
    private List<String>imageFileName;
    
    @Override
    public String execute() throws Exception
    {
        String path=ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println("保存路径为"+path);
      
//文件拷贝 
        if (image.size()>0)
        {
            File savedir=new File(path);
            if(!savedir.exists()) savedir.mkdirs(); 
            for (int i = 0; i < image.size(); i++)
            {
                System.out.println("datas的个数"+image.size());
                File saveFile=new File(savedir, imageFileName.get(i));
                FileUtils.copyFile(image.get(i), saveFile);
            }
        }else {
            System.out.println("datas为空");
        }
       
//文件拷贝的另一实现方式,还有一种是字节流去读取,比较原始,这里就省略了。
//        for (int i = 0; i < image.size(); i++)
//        {
//            File data=image.get(i);
//            String fileName=imageFileName.get(i);
//            fileName=path+"\\"+fileName;
//            data.renameTo(new File(fileName));
//        }
        return SUCCESS;
    }

    public List<File> getImage()
    {
        return image;
    }

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

    public List<String> getImageContentType()
    {
        return imageContentType;
    }

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

    public List<String> getImageFileName()
    {
        return imageFileName;
    }

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


第三步,编辑index.jsp用于上传,新建success.jsp用于上传成功后的提示,代码如下:

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</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:form action="upload" method="post" enctype="multipart/form-data" theme="simple">
    	<s:file name="image" label="Data1"></s:file>
    	<s:file name="image" label="Data2"></s:file>
    	<s:submit></s:submit>
    </s:form>
  </body>
</html>


success.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</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>
    	<h4>上传成功</h4>
    	<p><a href="download.jsp">下载文件</a></p>
    
  </body>
</html>



第四步,新建struts.xml并配置web.xml,代码如下:(注:从struts.xml中可以看到,我这里对文件类型进行了规定,只能上传txt或者xml格式的文件)

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
	
	<struts>
	<constant name="struts.multipart.saveDir" value="e:/"></constant>
		<package name="s2" extends="struts-default">
		<!-- 文件上传 -->
			<action name="upload" class="com.action.UploadAction">
				<result>success.jsp</result>
				<result name="input">index.jsp</result>
				<interceptor-ref name="fileUpload">
				<!-- 单个上传文件的最大值-->
				<param name="maximumSize">409600</param>
				<!-- 只能上传的文件的类型,可到tomcat的web-xml中查看各种文件类型-->
				<param name="allowedTypes">text/plain , text/xml</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			</action>
	
			
		</package>
	</struts>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <filter>
  <filter-name>s2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>s2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

第五步,部署项目并运行起来,键入http://localhost:8080/updownload/index.jsp,检验文件上传是否成功,成功的话会跳转到success,jsp提示成功,并在服务器的updownload的目录下自动创建images目录,并将上传的文件保存。假使不成功请根据报错检查项目并进行改正。


第六步,加入文件上传能功能,我们便接着在此基础上,完成文件的下载功能。

首先是新建com.action.DownloadAction.java,代码如下:

package com.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.regexp.internal.REUtil;

public class DownloadAction extends ActionSupport
{

    private static final long serialVersionUID = 1L;
    
    private Dao dao=new Dao();
    private List<FileItem>list;
    private String fileId;    
    private FileItem fileItem;
    
    //获得list
    public String list()
    {
        list=dao.getFileList();
        return "list-success";
    }
    //获得文件
    public String get()
    {
        fileItem=dao.getFileItem(fileId);
        return "get-success";
    }
    
    //获得输入流
    public InputStream getInputStream()
    {
        try
        {
            String path=ServletActionContext.getServletContext().getRealPath("/");
            String fileName=path+fileItem.getLocationPath();
            FileInputStream fis=new FileInputStream(fileName);
            return fis;
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    //获得文件类型
    public String getContentType()
    {
        return fileItem.getContentType();
    }
    
    //获得文件下载位置
    public String getContentDisposition()
    {
        try
        {
            return "attachment;filename="+URLEncoder.encode(fileItem.getFileName(),"utf-8");
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    //获得文件字节大小
    public int getContentLength()
    {
        return fileItem.getContentLength();
    }
    
    
    public List<FileItem> getList()
    {
        return list;
    }

    public void setList(List<FileItem> list)
    {
        this.list = list;
    }
    public String getFileId()
    {
        return fileId;
    }
    public void setFileId(String fileId)
    {
        this.fileId = fileId;
    }
    

}


第七步,新建一个com.action.FileItem.java的javabean,用来模拟数据库中对应的实体类,这里我们就模拟下。代码如下:

package com.action;


public class FileItem
{
    private String fileId;
    private String fileName;
    private String contentType;
    private String locationPath;
    private int contentLength;
   
    
    //getter和setter略
    
}

第八步,写一个Dao,这个Dao原本该去查询数据库,并得到下载列表的,但是我们这里只是讲解struts2,所以便不连接数据库,如第七步一样,我们模拟出查询列表的方法,当然,查到的下载列表,就是我们在上传功能中,已经上传到服务器的文件列表。

所以我们新建的com.action.Dao的代码如下:

package com.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Dao
{
    
    //静态数据,本该从数据库查出来的成为一个集合
    private static  Map<String, FileItem>files=new HashMap<String, FileItem>();
    static{
        long id=System.currentTimeMillis();
        String fileId="100"+id;
        files.put(fileId, new FileItem(fileId, "9-10.txt", "text/plain", "images\\9-10.txt", 206));
        fileId="200"+id;
        files.put(fileId, new FileItem(fileId, "aaa.xml", "text/xml", "images\\aaa.xml", 156));
        fileId="300"+id;
        files.put(fileId, new FileItem(fileId, "test.xml", "application/xml", "images\\test.xml", 617));
        fileId="400"+id;
        files.put(fileId, new FileItem(fileId, "Tomcat支持的文件类型.txt", "text/plain", "images\\Tomcat支持的文件类型.txt", 21*1024));
    }
    
    //获得文件下载列表
    public List<FileItem> getFileList()
    {
        return new ArrayList<FileItem>(files.values());
    }
    
    
    //根据id获得单个文件
    public FileItem getFileItem(String fileName)
    {
        return files.get(fileName);
    }
}

第九步:新建download.jsp和list-success.jsp,代码如下:

download.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'download.jsp' starting page</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>
	<a href="download_list">显示下载列表</a>
  </body>
  
  </html>br>
  </body>
</html>

list-success.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'list-success.jsp' starting page</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> 
    <h4>文件下载列表</h4>
    <s:iterator value="list">
    	<a href="download_get?fileId=${fileId} ">${fileName} </a>
    	<br/><br/>
    </s:iterator>
  </body>
</html>

第十步:修改struts.xml并在文件上传的下面,配置文件下载的action,并在src目录下,添加i18n.properties资源文件,对项目中的可能错误进行国际化,并在struts.xml中进行引用,即:<constant name="struts.custom.i18n.resources" value="i18n"></constant>



修改后的struts.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
	
	<struts>
	<constant name="struts.multipart.saveDir" value="e:/"></constant>
	<constant name="struts.custom.i18n.resources" value="i18n"></constant>
		<package name="s2" extends="struts-default">
		<!-- 文件上传 -->
			<action name="upload" class="com.action.UploadAction">
				<result>success.jsp</result>
				<result name="input">index.jsp</result>
				<interceptor-ref name="fileUpload">
				<!-- 单个上传文件的最大值-->
				<param name="maximumSize">409600</param>
				<!-- 只能上传的文件的类型,可到tomcat的web-xml中查看各种文件类型-->
				<param name="allowedTypes">text/plain , text/xml</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			</action>
		
		<!-- 文件下载 -->
			<action name="download_*" class="com.action.DownloadAction" method="{1}">
				<result name="{1}-success">{1}-success.jsp</result>
				<result name="get-success" type="stream"></result>
			</action>
			
		</package>
	</struts>
i18n.properties文件,代码如下:
struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u9519\u8BEF
struts.messages.error.file.too.large=\u6587\u4EF6\u8FC7\u5927
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8
struts.messages.error.file.extension.not.allowed=\u6587\u4EF6\u6269\u5C55\u540D\u4E0D\u5141\u8BB8
【csdn】的附件上传真实太坑了,还得先上传为资源,再提供下载链接,我这边儿都上传了,可是还是看不见链接,没办法,只能给出我的iteye链接,http://jackjobs.iteye.com/blog/1699240,它是直接能下载的,也不要积分什么的,为此,还得鄙视一下csdn这种附件下载积分的做法,(#‵′)凸















分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics