当前位置: 首页 > 编程笔记 >

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

韶亮
2023-03-14
本文向大家介绍JS+Struts2多文件上传实例详解,包括了JS+Struts2多文件上传实例详解的使用技巧和注意事项,需要的朋友参考一下

本文实例为大家分享了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);" />  
              &nbsp;  
              <input type="button" value="删除" />  
            </td>  
          </tr>  
          <tr id="op">  
            <td>  
              <input type="submit" id="uploadbutton" value="上传" />  
              &nbsp;  
              <input type="button" value="添加" id="addbutton" 
                onClick="addFileComponent();" />  
              &nbsp;  
            </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文件;

完毕!

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

 类似资料:
  • 本文向大家介绍Struts2+uploadify多文件上传实例,包括了Struts2+uploadify多文件上传实例的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了Struts2+uploadify多文件上传的具体代码,供大家参考,具体内容如下 首先我这里使用的是  Jquery  Uploadify3.2的版本 导入相关的CSS  JS   接下来是  上传的 JSP 页面代码

  • 本文向大家介绍struts2实现多文件上传,包括了struts2实现多文件上传的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了struts2实现多文件上传的具体代码,供大家参考,具体内容如下 首先搭建好struts2的开发环境,导入struts2需要的最少jar包 新建upload.jsp页面,注意一定要把表单的enctype设置成multipart/form-data 新建一个Up

  • 主要内容:1. 动作类,2. 结果页面,3. struts.xml,4. 示例,参考在上章节Struts2 文件上传示例, 用户允许选择一个文件并上传到服务器。在本教程中,您将学习如何允许用户将多个文件上传到服务器。 这里创建一个Web工程:strut2uploadfiles,来演示在多个复选框如何设置的默认值,整个项目的结构如下图所示: 1. 动作类 在Action类,可以使用列表或数组以存储上传的文件。 FileUploadAction.java 2. 结果页面 使用<s:f

  • 主要内容:1. 动作类,2. 结果页面,3. struts.xml,4. 示例,参考在Struts2, <s:file> 标签用于创建一个HTML文件上传组件,允许用户从本地磁盘选择文件,并将其上传到服务器。在本教程中,您将创建与文件上传组件JSP页面,设置最大大小和允许上传文件的内容类型,并显示上传文件的详细信息。 这里创建一个Web工程:strut2uploadfile,来演示在多个复选框如何设置的默认值,整个项目的结构如下图所示: 1. 动作类 Action类的文件上传,声

  • 本文向大家介绍struts2实现多文件上传的示例代码,包括了struts2实现多文件上传的示例代码的使用技巧和注意事项,需要的朋友参考一下 开发环境JDK1.8 eclipse struts2-2.3.31 1.创建web项目 2.导入struts2核心jar包 3.更改web.xml配置文件(只要配置好struts2的Filter就好) 4.创建src/struts.xml文件 5.创建src/

  • 主要内容:创建视图文件:,创建action类:,配置文件:,错误消息:Struts 2框架提供了内置支持处理文件上传使用基于HTML表单的文件上传。上传一个文件时,它通常会被存储在一个临时目录中,他们应该由Action类进行处理或移动到一个永久的目录,以确保数据不丢失。 请注意,服务器有一个安全策略可能会禁止写到目录以外的临时目录和属于web应用的目录。 在Struts中的文件上传是通过预先定义的拦截文件上传拦截器这是可通过org.apache.struts2.in