我是靠谱客的博主 无辜黑夜,最近开发中收集的这篇文章主要介绍JS+Struts2多文件上传完整示例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、JSP页面:
JS控制增加删除多个上传文件框,代码如下:
Java代码 复制代码
  1. <%@ page language="java" pageEncoding="UTF-8"%>   
  2. <%@ taglib prefix="s" uri="/struts-tags"%>   
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
  5. <html xmlns="http://www.w3.org/1999/xhtml">   
  6.     <head>   
  7.         <%@include file="../../_head.html"%>   
  8.         <title>文件上传</title>   
  9.         <meta http-equiv="pragma" content="no-cache">   
  10.         <meta http-equiv="cache-control" content="no-cache">   
  11.         <meta http-equiv="expires" content="0">   
  12.         <script language="javascript" type="text/javascript"  
  13.             src="../js/common/common.js"></script>   
  14.         <script type="text/javascript">   
  15.                 
  16.               var pos = 1;   
  17.            
  18.               function addFileComponent() {   
  19.                 var elTable = document.getElementById('uploadTable').getElementsByTagName('tbody')[0];   
  20.                 var elTr = document.getElementById('fileTr');   
  21.                 var elTr2 = document.getElementById('op');   
  22.                 var newEleTr = elTr.cloneNode(true);   
  23.                 newEleTr.id = "fileTr" + pos;          
  24.                 newEleTr.style.display = "";   
  25.                 inputs = newEleTr.getElementsByTagName('input');   
  26.                 inputs[0].id="file" + pos;   
  27.                 var elInput = inputs[1];   
  28.                 elInput.οnclick=delFileComponent;   
  29.                 elInput.id="delbutton" + pos++;   
  30.                 elTable.insertBefore(newEleTr, elTr2);   
  31.              }   
  32.   
  33.             function delFileComponent() {   
  34.                 var elTable = document.getElementById('uploadTable').getElementsByTagName('tbody')[0];   
  35.                 var trArr = elTable.getElementsByTagName("tr");   
  36.                 var el = event.srcElement;   
  37.                 for(j = 0; j < trArr.length; j++) {   
  38.                     tr = trArr[j];   
  39.                     if(tr.getElementsByTagName("input")[1] == el) {   
  40.                         elTable.removeChild(tr);   
  41.                         pos--;   
  42.                         break;   
  43.                     }   
  44.                 }   
  45.             }   
  46.                
  47.             function isValidateFile(obj){   
  48.                var extend = obj.value.substring(obj.value.lastIndexOf(".")+1);   
  49.                if(extend==""){   
  50.                }else{   
  51.                    if(!(extend=="xls"||extend=="doc")){   
  52.                       alert("请上传后缀名为xls或doc的文件!");   
  53.                       var nf = obj.cloneNode(true);   
  54.                       nf.value='';   
  55.                       obj.parentNode.replaceChild(nf, obj);   
  56.                       return false;   
  57.                    }   
  58.                }   
  59.                return true;   
  60.             }   
  61.         </script>   
  62.     </head>   
  63.     <body>   
  64.         <%@ include file="/common/message.jsp"%>   
  65.         <div class="body-box">   
  66.             <div class="rhead">   
  67.                 <div class="rpos">   
  68.                     文件上传(可同时上传多份文件)   
  69.                 </div>   
  70.                 <div class="clear"></div>   
  71.             </div>   
  72.             <s:form id="ops" action="csc_mUploadFile" theme="simple"  
  73.                 cssClass="rhead"  enctype = "multipart/form-data">   
  74.                 <table id="uploadTable" width="100%" border="0">   
  75.                     <tr>   
  76.                         <td>   
  77.                             <input type="file" id="file0" name="uploadFile" size="50"  
  78.                                 οnchange="isValidateFile(this);" />   
  79.                         </td>   
  80.                     </tr>   
  81.                     <tr id="fileTr" style="display: none;">   
  82.                         <td>   
  83.                             <input type="file" size="50" name="uploadFile"  
  84.                                 οnchange="isValidateFile(this);" />   
  85.                             &nbsp;   
  86.                             <input type="button" value="删除" />   
  87.                         </td>   
  88.                     </tr>   
  89.                     <tr id="op">   
  90.                         <td>   
  91.                             <input type="submit" id="uploadbutton" value="上传" />   
  92.                             &nbsp;   
  93.                             <input type="button" value="添加" id="addbutton"  
  94.                                 onClick="addFileComponent();" />   
  95.                             &nbsp;   
  96.                         </td>   
  97.                     </tr>   
  98.                 </table>   
  99.             </s:form>   
  100.             <table class="pn-ltable" width="100%" cellspacing="1" cellpadding="0"  
  101.                 border="0">   
  102.                 <thead class="pn-lthead">   
  103.                     <tr>   
  104.                         <th>   
  105.                             序号   
  106.                         </th>   
  107.                         <th>   
  108.                             文件名   
  109.                         </th>   
  110.                         <th>   
  111.                             上传时间   
  112.                         </th>   
  113.                     </tr>   
  114.                 </thead>   
  115.                 <tbody class="pn-ltbody">   
  116.                     <tr οnmοuseοver="Pn.LTable.lineOver(this);"  
  117.                         οnmοuseοut="Pn.LTable.lineOut(this);"  
  118.                         οnclick="Pn.LTable.lineSelect(this);">   
  119.                         <td>   
  120.                         </td>   
  121.                         <td>   
  122.                         </td>   
  123.                         <td>   
  124.                         </td>   
  125.                     </tr>   
  126.                 </tbody>   
  127.             </table>   
  128.         </div>   
  129.     </body>   
  130. </html>  
<%@ 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.οnclick=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"
οnchange="isValidateFile(this);" />
</td>
</tr>
<tr id="fileTr" style="display: none;">
<td>
<input type="file" size="50" name="uploadFile"
οnchange="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 οnmοuseοver="Pn.LTable.lineOver(this);"
οnmοuseοut="Pn.LTable.lineOut(this);"
οnclick="Pn.LTable.lineSelect(this);">
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>


2、Action后台处理上传文件:
Java代码 复制代码
  1.         //uploadFile对应页面<input type="file" name="uploadFile">  
  2. private List<File> uploadFile;   
  3.         //文件名对应uploadFile+“FileName”,要不获取不到文件名  
  4. private List<String> uploadFileFileName;      
  5. // 文件上传   
  6. public String mUploadFile() {   
  7.    if (null == uploadFile) {   
  8.     this.addActionError("请上传文件!");   
  9.    } else {   
  10.     String fileName = "";   
  11.       try {   
  12.                       //在自己代码中控制文件上传的服务器目录  
  13.          String directory = ServletActionContext.getServletContext().getRealPath("/uploads");   
  14.                       //判断该目录是否存在,不存在则创建  
  15.                       FileUtil.makeDir(directory);   
  16.                       //循环处理上传的文件  
  17.             for(int i=0,j=uploadFile.size();i<j;i++){   
  18.                 fileName = uploadFileFileName.get(i);   
  19.                 String filePath = directory + File.separator + fileName;   
  20.                 FileUtil.uploadFile(uploadFile.get(i), new File(filePath));   
  21.             }   
  22.         } catch (IOException e) {   
  23.                 this.addActionMessage("");   
  24.         }   
  25.            this.addActionMessage("文件上传成功!");   
  26.     }   
  27.     return "fileUpload";   
  28. }  

//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代码如下:
Java代码 复制代码
  1. public class FileUtil {   
  2.   
  3.     private static final int BUFFER_SIZE = 16 * 1024;   
  4.   
  5.     public static void uploadFile(File src, File dst) throws IOException {   
  6.   
  7.         InputStream in = null;   
  8.         OutputStream out = null;   
  9.         try {   
  10.             in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);   
  11.             out = new BufferedOutputStream(new FileOutputStream(dst),   
  12.                     BUFFER_SIZE);   
  13.             byte[] buffer = new byte[BUFFER_SIZE];   
  14.             while (in.read(buffer) > 0) {   
  15.                 out.write(buffer);   
  16.             }   
  17.         } finally {   
  18.             if (null != in) {   
  19.                 in.close();   
  20.             }   
  21.             if (null != out) {   
  22.                 out.close();   
  23.             }   
  24.         }   
  25.   
  26.     }   
  27.   
  28.     public static String getExtention(String fileName) {   
  29.         int pos = fileName.lastIndexOf(".");   
  30.         return fileName.substring(pos);   
  31.     }   
  32.   
  33.     public static void makeDir(String directory) {   
  34.         File dir = new File(directory);   
  35.   
  36.         if (!dir.isDirectory()) {   
  37.             dir.mkdirs();   
  38.         }   
  39.   
  40.     }   
  41.   
  42.     public static String generateFileName(String fileName)   
  43.             throws UnsupportedEncodingException {   
  44.         DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
  45.         String formatDate = format.format(new Date());   
  46.         String extension = fileName.substring(fileName.lastIndexOf("."));   
  47.         fileName = new String(fileName.getBytes("iso8859-1"), "gb2312");   
  48.         return fileName + "_" + formatDate + new Random().nextInt(10000)   
  49.                 + extension;   
  50.     }   
  51.   
  52. }  
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文件;

完毕!


  转载请标明出处 http://blog.csdn.net/shimiso 

技术交流群:361579846

 

最后

以上就是无辜黑夜为你收集整理的JS+Struts2多文件上传完整示例的全部内容,希望文章能够帮你解决JS+Struts2多文件上传完整示例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(31)

评论列表共有 0 条评论

立即
投稿
返回
顶部