struts上传下载多个文件

实例:
第一步导入包:
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
xwork-core-2.1.6.jar
struts.jar
commons-beanutils-1.7.0.jar
commons-digester.jar
第二上传upload,jsp、下载download.jsp的jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="/WEB-INF/taglib/struts-html.tld" prefix="html" %>
<html:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
<!--addMore函数可以提供上传多个文件上传-->
    var index = 1;
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["+index+"]";
    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);
    index ++;
}
</script>
</head>
<body>
<!--<h3><font color="red">上传文件类型后缀为doc,ppt,xls,pdf,txt,java,每个文件大小不能大于50M</font></h3>-->
        <html:form action="/UpDownLoadAction.do?dispatch=upLoadFile"  method="post" enctype="multipart/form-data">
            <table align="center" width="50%" border="1">
                <tr>
                    <td>
                        上传文件
                    </td>
                    <td id="more" >
                        <input  type="file" id="file_0" name="file[0]"/>
                        <input type="button" value="上传更多..." onclick="addMore()">
                    </td>
                </tr>
                <tr>
                    <td>
                        <html:submit value=" 确认 "></html:submit>
                    </td>
                    <td>
                        <html:reset value=" 重置 "></html:reset>
                    </td>
                </tr>
            </table>
        </html:form>
    </body>
</html:html>

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="demo.updown.file.model.UploadFiles"%>
<%@page import="java.util.*;"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>文件下载</title>
</head>
<body>
<table align="center" width="50%" border="1">
    <tr><td align="center">文件下载</td></tr>
<%List files = (ArrayList)request.getAttribute("fileList");
for(int i = 0;i<files.size();i++){
UploadFiles file = (UploadFiles)files.get(i);%>
        <tr>
            <td>
                <a href="/updownfile/UpDownLoadAction.do?dispatch=downLoadFile&name=<%=file.getUploadRealName() %>&realname=<%=file.getUploadFileName() %>">
                        <%=file.getUploadFileName() %></a>
            </td>
        </tr>
    <%} %>
    </table>
</body>
</html>


第三步实体类(前台要显示的数据信息)
public class UploadFiles {
    private String uploadFileName;//上传的文件名称
    private String uploadContentType;//类型
    private String uploadRealName;//保存的文件真实名称,UUID

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadRealName() {
        return uploadRealName;
    }

    public void setUploadRealName(String uploadRealName) {
        this.uploadRealName = uploadRealName;
    }

第四步上传的业务接口与实现类
public class UpDownLoadImpl implements UpDownLoad{

    String path = "E:/apache-tomcat/apache-tomcat-6.0.18/webapps/updownfile/file";
    public UploadFiles uploadfile(FormFile file) throws IOException {
        // TODO Auto-generated method stub
        String fileName = file.getFileName();//原文件名
        String realName = UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."));//保存的文件名称,使用UUID+后缀进行保存
        //创建文件夹,保存上传文件
        File filepath = new File(path);
        if (!filepath.isDirectory()) {
            filepath.mkdir();
        }
        //文件上传后的路径
        String filePath = filepath + "/" + realName;
       
        InputStream stream = file.getInputStream();
        OutputStream bos = new FileOutputStream(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();
        stream.close();
       
        //页面上显示上传的文件信息
        UploadFiles files = new UploadFiles();
        files.setUploadFileName(file.getFileName());
        files.setUploadContentType(file.getContentType());
        files.setUploadRealName(realName);
       
        return files;
    }
}

第五步action
public class UpLoadActionForm extends ActionForm {

    private static final long serialVersionUID = 1L;
    /**
     * struts1文件上传用的是调用的是专门上传的接口FormFile,
     * 单文件上传只需在Form中给一个FormFile类型的属性,
     * 多文件上传时,struts在页面端将多个文件封装成一个数组,转给Form类时转换成List
     * 所以我们在页面上使用数组形式对文件进行提交,在Form类中用List对文件进行接收。
     *
     * */
    private List<FormFile> files = new ArrayList<FormFile>();

    public FormFile getFile(int i) {
        return files.get(i);
    }

    public void setFile(int i,FormFile file) {
        files.add(file);
    }
   
    public List getFiles(){
        return files;
    }
}

public class UpDownLoadAction extends DispatchAction {
    /**
     * 上传文件
     * */
    public ActionForward upLoadFile(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ActionForward forward = null;
        ActionMessages errors = new ActionMessages();

        UpLoadActionForm upLoad = (UpLoadActionForm) form;
        List upLoads = upLoad.getFiles();
       
        UpDownLoad updownload = new UpDownLoadImpl();
        List fileList = new ArrayList();
        for(int i = 0;i<upLoads.size();i++){
            FormFile formFile = (FormFile) upLoads.get(i);
            //调用单个文件上传的方法
            UploadFiles files = updownload.uploadfile(formFile);
            System.out.println("上传文件:" + files.getUploadFileName());
            fileList.add(files);
        }
        request.setAttribute("fileList", fileList);
        return mapping.findForward("download");
    }

    /**
     * 文件下载
     * */
    public ActionForward downLoadFile(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        String filename = request.getParameter("name");
        String realname = request.getParameter("realname");

        response.reset();//可以加也可以不加
        response.setContentType("application/x-download");//设置为下载application/x-download
        /*
         * 这个属性设置的是下载工具下载文件时显示的文件名,要想正确的显示中文文件名,我们需要对fileName再次编码
         * 否则中文名文件将出现乱码,或无法下载的情况
         */
        realname = URLEncoder.encode(realname, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename="+ realname);//下载文件时,显示的文件名

        //下载文件的路径
        String path = this.servlet.getServletContext().getRealPath("/file") + "/" + filename;

        OutputStream output = response.getOutputStream();
        FileInputStream fis = new FileInputStream(path);

        byte[] b = new byte[1024];
        int i = 0;

        while ((i = fis.read(b)) > 0) {
            output.write(b, 0, i);
        }
        output.flush();
        fis.close();
        output.close();

        return null;
    }

}

第六步web.xml和struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
            org.apache.struts.action.ActionServlet
        </servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>3</param-value>
        </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>3</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
    <struts-config>
        <form-beans>
            <form-bean name="UpLoadActionForm"
                type="demo.updown.file.actionform.UpLoadActionForm" />
        </form-beans>
       
        <action-mappings>
            <action path="/UpDownLoadAction" name="UpLoadActionForm" parameter="dispatch"
            scope="request"
            type="demo.updown.file.action.UpDownLoadAction"
            validate="true">
                <forward name="download" path="/download.jsp"></forward>
            </action>
        </action-mappings>
    </struts-config>

猜你喜欢

转载自lanxulin.iteye.com/blog/2207561