欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS+Struts2多文件上传实例详解

程序员文章站 2024-02-26 12:57:28
本文实例为大家分享了js struts2多文件上传的具体代码,供大家参考,具体内容如下 1、jsp页面: js控制增加删除多个上传文件框,代码如下:...

本文实例为大家分享了js struts2多文件上传的具体代码,供大家参考,具体内容如下

1、jsp页面:

js控制增加删除多个上传文件框,代码如下:

<%@ page language="java" pageencoding="utf-8"%>  
<%@ taglib prefix="s" uri="/struts-tags"%>  
 
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
  <head>  
    <%@include file="../../_head.html"%>  
    <title>文件上传</title>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">  
    <script language="javascript" type="text/javascript" 
      src="../js/common/common.js"></script>  
    <script type="text/javascript">  
        
       var pos = 1;  
      
       function addfilecomponent() {  
        var eltable = document.getelementbyid('uploadtable').getelementsbytagname('tbody')[0];  
        var eltr = document.getelementbyid('filetr');  
        var eltr2 = document.getelementbyid('op');  
        var neweletr = eltr.clonenode(true);  
        neweletr.id = "filetr" + pos;     
        neweletr.style.display = "";  
        inputs = neweletr.getelementsbytagname('input');  
        inputs[0].id="file" + pos;  
        var elinput = inputs[1];  
        elinput.onclick=delfilecomponent;  
        elinput.id="delbutton" + pos++;  
        eltable.insertbefore(neweletr, eltr2);  
       }  
 
      function delfilecomponent() {  
        var eltable = document.getelementbyid('uploadtable').getelementsbytagname('tbody')[0];  
        var trarr = eltable.getelementsbytagname("tr");  
        var el = event.srcelement;  
        for(j = 0; j < trarr.length; j++) {  
          tr = trarr[j];  
          if(tr.getelementsbytagname("input")[1] == el) {  
            eltable.removechild(tr);  
            pos--;  
            break;  
          }  
        }  
      }  
        
      function isvalidatefile(obj){  
        var extend = obj.value.substring(obj.value.lastindexof(".")+1);  
        if(extend==""){  
        }else{  
          if(!(extend=="xls"||extend=="doc")){  
           alert("请上传后缀名为xls或doc的文件!");  
           var nf = obj.clonenode(true);  
           nf.value='';  
           obj.parentnode.replacechild(nf, obj);  
           return false;  
          }  
        }  
        return true;  
      }  
    </script>  
  </head>  
  <body>  
    <%@ include file="/common/message.jsp"%>  
    <div class="body-box">  
      <div class="rhead">  
        <div class="rpos">  
          文件上传(可同时上传多份文件)  
        </div>  
        <div class="clear"></div>  
      </div>  
      <s:form id="ops" action="csc_muploadfile" theme="simple" 
        cssclass="rhead" enctype = "multipart/form-data">  
        <table id="uploadtable" width="100%" border="0">  
          <tr>  
            <td>  
              <input type="file" id="file0" name="uploadfile" size="50" 
                onchange="isvalidatefile(this);" />  
            </td>  
          </tr>  
          <tr id="filetr" style="display: none;">  
            <td>  
              <input type="file" size="50" name="uploadfile" 
                onchange="isvalidatefile(this);" />  
                 
              <input type="button" value="删除" />  
            </td>  
          </tr>  
          <tr id="op">  
            <td>  
              <input type="submit" id="uploadbutton" value="上传" />  
                 
              <input type="button" value="添加" id="addbutton" 
                onclick="addfilecomponent();" />  
                 
            </td>  
          </tr>  
        </table>  
      </s:form>  
      <table class="pn-ltable" width="100%" cellspacing="1" cellpadding="0" 
        border="0">  
        <thead class="pn-lthead">  
          <tr>  
            <th>  
              序号  
            </th>  
            <th>  
              文件名  
            </th>  
            <th>  
              上传时间  
            </th>  
          </tr>  
        </thead>  
        <tbody class="pn-ltbody">  
          <tr onmouseover="pn.ltable.lineover(this);" 
            onmouseout="pn.ltable.lineout(this);" 
            onclick="pn.ltable.lineselect(this);">  
            <td>  
            </td>  
            <td>  
            </td>  
            <td>  
            </td>  
          </tr>  
        </tbody>  
      </table>  
    </div>  
  </body>  
</html> 

2、action后台处理上传文件:

//uploadfile对应页面<input type="file" name="uploadfile"> 
private list<file> uploadfile;  
//文件名对应uploadfile+“filename”,要不获取不到文件名 
private list<string> uploadfilefilename;   
// 文件上传  
public string muploadfile() {  
  if (null == uploadfile) {  
  this.addactionerror("请上传文件!");  
  } else {  
  string filename = "";  
   try {  
           //在自己代码中控制文件上传的服务器目录 
     string directory = servletactioncontext.getservletcontext().getrealpath("/uploads");  
           //判断该目录是否存在,不存在则创建 
           fileutil.makedir(directory);  
           //循环处理上传的文件 
      for(int i=0,j=uploadfile.size();i<j;i++){  
        filename = uploadfilefilename.get(i);  
        string filepath = directory + file.separator + filename;  
        fileutil.uploadfile(uploadfile.get(i), new file(filepath));  
      }  
    } catch (ioexception e) {  
        this.addactionmessage("");  
    }  
      this.addactionmessage("文件上传成功!");  
  }  
  return "fileupload";  
}

fileutil代码如下:

public class fileutil {
 
 private static final int buffer_size = 16 * 1024;
 
 public static void uploadfile(file src, file dst) throws ioexception {
 
 inputstream in = null;
 outputstream out = null;
 try {
  in = new bufferedinputstream(new fileinputstream(src), buffer_size);
  out = new bufferedoutputstream(new fileoutputstream(dst),
   buffer_size);
  byte[] buffer = new byte[buffer_size];
  while (in.read(buffer) > 0) {
  out.write(buffer);
  }
 } finally {
  if (null != in) {
  in.close();
  }
  if (null != out) {
  out.close();
  }
 }
 
 }
 
 public static string getextention(string filename) {
 int pos = filename.lastindexof(".");
 return filename.substring(pos);
 }
 
 public static void makedir(string directory) {
 file dir = new file(directory);
 
 if (!dir.isdirectory()) {
  dir.mkdirs();
 }
 
 }
 
 public static string generatefilename(string filename)
  throws unsupportedencodingexception {
 dateformat format = new simpledateformat("yymmddhhmmss");
 string formatdate = format.format(new date());
 string extension = filename.substring(filename.lastindexof("."));
 filename = new string(filename.getbytes("iso8859-1"), "gb2312");
 return filename + "_" + formatdate + new random().nextint(10000)
  + extension;
 }
 
}

扩展:

1.可以实现带进度条的上传与下载;
2.可以用xml文件记录上传的文件清单,并且可以根据页面对上传文件的操作来修改相应的xml文件;

完毕!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。