服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

j2ee综合:struts上传多个文件的例子

最近一个基于struts的项目中要用到上传多张图片到系统中,我在网上找了一下,发现大多数都是转载的例子,对项目的作用不大,故写下了这个例子,希望对有用到的朋友有所帮助。要求jdk1.5以上,lib库要包含如下jar文件:antlr.jar,commons-beanutils.jar,commons-collections.jar,commons-digester.jar,commons-fileupload.jar,commons-logging.jar,commons-validator.jar,jakarta-oro.jar,struts.jar这些都是struts中的jar文件以及struts中的标签库文件。
    //可以转载,请保留出自http://www.javaresearch.org,作者anengineer

一。web.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>actionservlet< /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>2< /param-value>
        < /init-param>
        < load-on-startup>0< /load-on-startup>
    < /servlet>
    < !-- struts actionservlet mapping-->
    < servlet-mapping>
        < servlet-name>actionservlet< /servlet-name>
        < url-pattern>*.do< /url-pattern>
    < /servlet-mapping>
    < !-- welcome file list -->
    < welcome-file-list>
         < welcome-file>index.jsp< /welcome-file>
    < /welcome-file-list>
    < !-- error handle -->
    < error-page>
         < error-code>404< /error-code>
         < location>/error.jsp< /location>
    < /error-page>
< /web-app>

二。struts-config.xml文件

< ?xml version="1.0" encoding="iso-8859-1" ?>   
< !doctype struts-config public
          "-//apache software foundation//dtd struts configuration 1.2//en"
          "http://struts.apache.org/dtds/struts-config_1_2.dtd">
< struts-config>
     < !-- form beans -->
     < form-beans>
         < form-bean name="uploadform" type="org.apache.struts.action.dynaactionform">
            < form-property name="type" type ="java.lang.string[]"/>
            < form-property name="name" type ="java.lang.string[]"/>
              < form-property name="file0" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file1" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file2" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file3" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file4" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file5" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file6" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file7" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file8" type ="org.apache.struts.upload.formfile"/>
            < form-property name="file9" type ="org.apache.struts.upload.formfile"/>
         < /form-bean>
     < /form-beans>
     < !-- forward -->
     < global-forwards>
          < forward name= "successed" path="/index.jsp">< /forward>   
          < forward name= "failed" path="/error.jsp">< /forward>   
     < /global-forwards>
     < !-- action handle-->
     < action-mappings>
          < action path="/uploaded" type="com.fangchuang.action.uploadaction"
                  name="uploadform" scope="request" input="/upload.jsp">
                < forward name="uploaded" path="/upload.jsp">< /forward>
          < /action>
     < /action-mappings>
< /struts-config>

三。upload.jsp文件
< %@ page language="java" import="java.util.*" pageencoding="gb2312" errorpage="error.jsp"%>

< %@ taglib uri="/web-inf/struts-html.tld" prefix="html"%>
< %@ taglib uri="/web-inf/struts-bean.tld" prefix="bean"%>
< %@ taglib uri="/web-inf/struts-logic.tld" prefix="logic"%>
< %@ taglib uri="/web-inf/struts-tiles.tld" prefix="title"%>

< !-- 上传多个文件的jsp文件
     //可以随便转载,请保留出自http://www.javaresearch.org 作者anengineer
-->
< html>
< head>
< title>上传多个文件的jsp文件< /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="struts,多个文件,上传">
< meta http-equiv="description" content="this is a test">
< /head>
< body>

< html:form action="uploaded.do" enctype="multipart/form-data" method="post">
    < table border="1" width="80%" align="center">
        < tr bgcolor=#62bcff>
            < td align="left">文件类型< /td>
            < td align="left">文件描述< /td>
            < td align="left">文件名< /td>
        < /tr>

        < tr>
            < td align="left">< select name="type">
                < option value="1" selected>湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file0" size="35" value="">
            < /td>
        < /tr>


        < tr>
            < td align="left">< select name="type">
                < option value="1"selected>湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file1" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2"selected>湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file2" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2"selected>湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file3" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3"selected>广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file4" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3"selected>广东省< /option>
                < option value="4">北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file5" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4"selected>北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file6" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4"selected>北京市< /option>
                < option value="5">上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file7" size="35" value="">
            < /td>
        < /tr>
        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5"selected>上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file8" size="35" value="">
            < /td>
        < /tr>


        < tr>
            < td align="left">< select name="type">
                < option value="1">湖南省< /option>
                < option value="2">湖北省< /option>
                < option value="3">广东省< /option>
                < option value="4">北京市< /option>
                < option value="5"selected>上海市< /option>
            < /select>< /td>

            < td align="left">< input type="text" name="name" value="">< /td>

            < td align="left">< input type="file" name="file9" size="35" value="">
            < /td>
        < /tr>

        < tr>
            < td align="left"> < /td>
            < td align="left"> < /td>
            < td align="left">< input type="submit" value="上传文件" value="submit"
                onclick="return(confirm('你确认要上传文件吗?'))">< /td>
        < /tr>

    < /table>
< /html:form>

< /body>
< /html>

四。还有两个简单jsp文件index.jsp,error.jsp可以自己写。

五。action文件

package com.fangchuang.action;
/**
 * @author anengineer 处理上传文件action
 */
public class uploadaction extends action {
    public actionforward execute(
            actionmapping mapping,
            actionform form,
            httpservletrequest request,
            httpservletresponse response) {
        //可以随便转载,请保留出自http://www.javaresearch.org 作者anengineer
        dynaactionform fileform = (dynaactionform) form;
        string[] types = (string[]) fileform.get("type");
        string[] names = (string[]) fileform.get("name");

        formfile file0 = (formfile) fileform.get("file0");
        formfile file1 = (formfile) fileform.get("file1");
        formfile file2 = (formfile) fileform.get("file2");
        formfile file3 = (formfile) fileform.get("file3");
        formfile file4 = (formfile) fileform.get("file4");
        formfile file5 = (formfile) fileform.get("file5");
        formfile file6 = (formfile) fileform.get("file6");
        formfile file7 = (formfile) fileform.get("file7");
        formfile file8 = (formfile) fileform.get("file8");
        formfile file9 = (formfile) fileform.get("file9");

        map< string, formfile> filemap = new hashmap< string, formfile>();
        filemap.put("file0" + "*" + types[0] + "*" + names[0], file0);
        filemap.put("file1" + "*" + types[1] + "*" + names[1], file1);
        filemap.put("file2" + "*" + types[2] + "*" + names[2], file2);
        filemap.put("file3" + "*" + types[3] + "*" + names[3], file3);
        filemap.put("file4" + "*" + types[4] + "*" + names[4], file4);
        filemap.put("file5" + "*" + types[5] + "*" + names[5], file5);
        filemap.put("file6" + "*" + types[6] + "*" + names[6], file6);
        filemap.put("file7" + "*" + types[7] + "*" + names[7], file7);
        filemap.put("file8" + "*" + types[8] + "*" + names[8], file8);
        filemap.put("file9" + "*" + types[9] + "*" + names[9], file9);

        set fileset = filemap.entryset();
        iterator iter = fileset.iterator();

        // 取当前系统路径e:\tomcat5\webapps\strutsupload\ 其中strutsupload为当前context
        string filepath = this.getservlet().getservletcontext().getrealpath("/");
        // 保存文件的文件夹
        file savepath = new file(filepath + "uploadfiles\\");
        filepath = filepath+ "uploadfiles\\";
        if (!savepath.exists()) {
            savepath.mkdir();
        }
        while (iter.hasnext()) {
            map.entry unit = (map.entry) iter.next();
            string key = (string) unit.getkey();
            formfile file = (formfile) unit.getvalue();   
            //文件大小符合要求,且是图片文件
            if ((file.getfilesize() >= 1)&& dealphoto.isphoto(file)) {
                //图片类别
                string phototype = key.substring(key.indexof("*") + 1, key
                        .lastindexof("*"));
                //图片描述
                string photoname = key.substring(key.lastindexof("*") + 1, key
                        .length());
               
                //存数据库操作,在数据库中保存文件的名称,类型,及在服务器上的相对路径
                //
               
                //判断是否重名
                if(dealphoto.isfileexist(file.getfilename(),filepath))
                    dealphoto.rename(file.getfilename(),filepath);
                try {
                 inputstream stream = file.getinputstream();// 把文件读入
                 // 建立一个上传文件的输出流
                 outputstream bos = new fileoutputstream(filepath+file.getfilename());
                 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();
                } catch (exception e) {
                    e.printstacktrace();
                }
            }

        }
        return mapping.findforward("uploaded");
        //还有其他可以改正的地方,如错误信息提示,把照片处理函数放到一个公用类,写文件操作等
        //可以随便转载,请保留出自http://www.javaresearch.org 作者anengineer
    }
}

六。照片处理类文件
package com.fangchuang.run;
/**
 * 图片处理
 * @author anengineer
 *
 */
public class dealphoto {
    /**
     * 判断照片类型 .jpg .png .gif 目前只支持这三种格式
     * @param file
     * @return
     */
    public static boolean isphoto(formfile file) {
        string filename = getstring(file.getfilename());
        if (filename.equals(""))
            return false;
        if ((filename.tolowercase().endswith(".jpg"))
                || (filename.tolowercase().endswith(".gif"))
                || (filename.tolowercase().endswith(".png")))
            return true;
        else
            return false;
    }

    /**
     *
     * @param str
     * @return
     */
    public static string getstring(string str) {
        if (str == null)
            str = "";
        if (str.equals("null"))
            str = "";
        str = str.trim();
        return str;
    }

    /**
     * 判断文件是否存在
     * @param filename
     * @param dir
     * @return
     */
    public static boolean isfileexist(string filename, string dir) {
        file files = new file(dir + filename);
        return (files.exists()) ? true : false;
    }

    /**
     * 重命名
     * @param filename
     * @param dir
     */
    public static void rename(string filename, string dir) {
        string extendfile = "";
        if (isjpg(filename))
            extendfile = ".jpg";
        else if (isgif(filename))
            extendfile = ".gif";
        else if (ispng(filename))
            extendfile = ".png";
        else
            extendfile = ".jpg";
        random random = new random();
        int add = random.nextin