分享

struts2 多文件上传下载

 怀旧妞妞 2010-11-26

第一步:首先导入Struts2的开发包和commons-fileupload-1.2.1.jar,commons-io-1.4.jar.(这些开发包都放在工程的lib目录下)
第二步:用过滤器在web.xml中配置Struts2的核心控制器。
<!-- 配置struts2过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第三步: 上传的upload.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 'upload.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">
-->
<script type="text/javascript">
function addMore(){
var td=document.getElementById("more");
var br=document.createElement("br");
var input=document.createElement("input");
var button=document.createElement("input");

input.type="file";
input.name="file";

button.type="button";
button.value="删除";

button.onclick=function(){
td.removeChild(br);
td.removeChild(input);
td.removeChild(button);
}

td.appendChild(br);
td.appendChild(input);
td.appendChild(button);
}
</script>

</head>

<body>
<s:fielderror cssStyle="color:red;"/>


   <s:form action="upload!Upload.action" method="post" enctype="multipart/form-data">
    <table align="center" width="60%" border="1">
     <tr>
      <td>
       选择上传的文件:
      </td>
      <td id="more">
       <%--<s:file name="file" label="选择上传的文件"></s:file>--%>
       <input type="file" name="file">
       <input type="button" value="继续添加" onclick="addMore()" />
      </td>
     </tr>
     <tr>
      <td>
      </td>
      <td>
       <s:submit value="上传" align="center"></s:submit>
      </td>
     </tr>
    </table>
   </s:form>
</body>
</html>

第四步:后台UploadAction.java

package com.struts2.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

private List<File> file;
private List<String> fileFileName;
private List<String> fileContentType;


public List<File> getFile() {
   return file;
}
public void setFile(List<File> file) {
   this.file = file;
}
public List<String> getFileFileName() {
   return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
   this.fileFileName = fileFileName;
}
public List<String> getFileContentType() {
   return fileContentType;
}
public void setFileContentType(List<String> fileContentType) {
   this.fileContentType = fileContentType;
}

public String Upload() throws IOException {

   InputStream is=null;
   OutputStream os=null;
   for(int i=0;i<file.size();i++){
   try{
   is=new FileInputStream(file.get(i));
   String root=ServletActionContext.getRequest().getRealPath("/upload");
   File destFile=new File(root+"/",this.getFileFileName().get(i));
   // File destFile=new File(root,this.getFileFileName().get(i));
   os=new FileOutputStream(destFile);
   byte [] b=new byte[400];
   int length=0;
   while((length=is.read(b))>0){
   os.write(b,0,length);
   // os.write(b); 这样子同样可行
   }
   }catch(Exception ex){
   ex.printStackTrace();
   }finally{
   is.close();
   os.close();
   }
      }
   return "show";
   }

}

第五步:在src建一个Struts2的配置文件 struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts./dtds/struts-2.0.dtd">
<struts>

<!--定义全局错误文件message,把后面的文件类型和文件超过设定大小的信息写在message.properties-->
<constant name="struts.custom.i18n.resources" value="message"></constant>

<include file="struts-default.xml"></include>
<!-- 这里设置编码方式,注意上传页面也要用此编码方式,否则得到的文件名是乱码 -->
<constant name="struts.i18n.encoding" value="utf-8"></constant>

<constant name="struts.multipart.saveDir" value="d:\struts2upload\"></constant>

<package name="default" extends="struts-default">
   <action name="upload" <result name="upload">/upload.jsp</result>
    <result name="show">/show.jsp</result>
    <result name="input">/upload.jsp</result>

    <!-- 定义拦截器 拦截上传的文件格式,上传的单个文件的大小 注:文件格式可以参考tomcat下conf下web.xml 的一些文件格式 -->
    <interceptor-ref name="fileUpload">
     <param name="allowedTypes">
      image/bmp,image/png,image/gif,image/jpeg,application/msword,audio/x-mpeg,text/html,text/plain
     </param>

    <param name="maximumSize">409600</param>
    </interceptor-ref>

    <interceptor-ref name="defaultStack"></interceptor-ref>
   </action>

</package>
</struts>

在运行上述例子,如果您留心一点的话,应该会发现服务器控制台有如下输出:

Mar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.dispatcher.Dispatcher getSaveDir
INFO: Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir
Mar
20 , 2007 4 : 08 : 43 PM org.apache.struts2.interceptor.FileUploadInterceptor intercept
INFO: Removing file myFile C:\Program Files\Tomcat
5.5 \work\Catalina\localhost\Struts2_Fileupload\upload_251447c2_1116e355841__7ff7_00000006.tmp

清单9 服务器控制台输出

上述信息告诉我们,struts.multipart.saveDir没有配置。struts.multipart.saveDir用于指定存放临时文件的文件夹,该配置写在struts.properties文件中。例如,如果在struts.properties文件加入如下代码:

struts.multipart.saveDir = /tmp

 

如果文件类型过大,或者文件类弄不允许,要显示错误信息

message.properties
错误显示
xwork.default.invalid.fieldvalue={0} error
struts.messages.error.content.type.not.allowed=\u6b64\u79cd\u6587\u4ef6\u7c7b\u578b\u4e0d\u5141\u8bb8\u4e0a\u4f20!
struts.messages.error.file.too.large=\u4e0a\u4f20\u7684\u6587\u4ef6\u592a\u5927\uff0c\u8bf7\u91cd\u8bd5\uff01
struts.messages.error.uploading=\u6587\u4ef6\u5728\u4e0a\u4f20\u8fc7\u7a0b\u4e2d\u53d1\u751f\u4e86\u9519\u8bef\uff0c\u8bf7\u91cd\u8bd5\uff01

 

 


清单10 struts配置

这样上传的文件就会临时保存到你根目录下的tmp文件夹中(一般为c:\tmp),如果此文件夹不存在,Struts 2会自动创建一个。

文件下载:(以下载PPT为例)

01 download.jsp

<a href="/项目名/download.action">点击下载</a>

02 downloadAction.java

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;

public InputStream getDownloadFile(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts.ppt");
}

execute{
return SUCCESS;
}

03 struts.xml

struts.xml

<action name="download" name="success" type="stream">
   <param name="contentType">application/vnd.ms-powerpoint</param>
   <param name="contentDisposition">filename="struts.ppt"</param>
   <param name="inputName">downloadFile</param>
</result>
</action>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多