JS+Struts2多文件上传完整示例

本文介绍了一个使用JSP实现的文件上传功能,包括前端页面的文件输入与动态增删功能,以及后端通过Struts框架接收并处理上传文件的过程。此外,还提供了一个文件处理工具类用于文件上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、JSP页面:
JS控制增加删除多个上传文件框,代码如下:
Java代码 复制代码
  1. <%@pagelanguage="java"pageEncoding="UTF-8"%>
  2. <%@taglibprefix="s"uri="/struts-tags"%>
  3. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <htmlxmlns="http://www.w3.org/1999/xhtml">
  5. <head>
  6. <%@includefile="../../_head.html"%>
  7. <title>文件上传</title>
  8. <metahttp-equiv="pragma"content="no-cache">
  9. <metahttp-equiv="cache-control"content="no-cache">
  10. <metahttp-equiv="expires"content="0">
  11. <scriptlanguage="javascript"type="text/javascript"
  12. src="../js/common/common.js"></script>
  13. <scripttype="text/javascript">
  14. varpos=1;
  15. functionaddFileComponent(){
  16. varelTable=document.getElementById('uploadTable').getElementsByTagName('tbody')[0];
  17. varelTr=document.getElementById('fileTr');
  18. varelTr2=document.getElementById('op');
  19. varnewEleTr=elTr.cloneNode(true);
  20. newEleTr.id="fileTr"+pos;
  21. newEleTr.style.display="";
  22. inputs=newEleTr.getElementsByTagName('input');
  23. inputs[0].id="file"+pos;
  24. varelInput=inputs[1];
  25. elInput.onclick=delFileComponent;
  26. elInput.id="delbutton"+pos++;
  27. elTable.insertBefore(newEleTr,elTr2);
  28. }
  29. functiondelFileComponent(){
  30. varelTable=document.getElementById('uploadTable').getElementsByTagName('tbody')[0];
  31. vartrArr=elTable.getElementsByTagName("tr");
  32. varel=event.srcElement;
  33. for(j=0;j<trArr.length;j++){
  34. tr=trArr[j];
  35. if(tr.getElementsByTagName("input")[1]==el){
  36. elTable.removeChild(tr);
  37. pos--;
  38. break;
  39. }
  40. }
  41. }
  42. functionisValidateFile(obj){
  43. varextend=obj.value.substring(obj.value.lastIndexOf(".")+1);
  44. if(extend==""){
  45. }else{
  46. if(!(extend=="xls"||extend=="doc")){
  47. alert("请上传后缀名为xls或doc的文件!");
  48. varnf=obj.cloneNode(true);
  49. nf.value='';
  50. obj.parentNode.replaceChild(nf,obj);
  51. returnfalse;
  52. }
  53. }
  54. returntrue;
  55. }
  56. </script>
  57. </head>
  58. <body>
  59. <%@includefile="/common/message.jsp"%>
  60. <divclass="body-box">
  61. <divclass="rhead">
  62. <divclass="rpos">
  63. 文件上传(可同时上传多份文件)
  64. </div>
  65. <divclass="clear"></div>
  66. </div>
  67. <s:formid="ops"action="csc_mUploadFile"theme="simple"
  68. cssClass="rhead"enctype="multipart/form-data">
  69. <tableid="uploadTable"width="100%"border="0">
  70. <tr>
  71. <td>
  72. <inputtype="file"id="file0"name="uploadFile"size="50"
  73. onchange="isValidateFile(this);"/>
  74. </td>
  75. </tr>
  76. <trid="fileTr"style="display:none;">
  77. <td>
  78. <inputtype="file"size="50"name="uploadFile"
  79. onchange="isValidateFile(this);"/>
  80. &nbsp;
  81. <inputtype="button"value="删除"/>
  82. </td>
  83. </tr>
  84. <trid="op">
  85. <td>
  86. <inputtype="submit"id="uploadbutton"value="上传"/>
  87. &nbsp;
  88. <inputtype="button"value="添加"id="addbutton"
  89. onClick="addFileComponent();"/>
  90. &nbsp;
  91. </td>
  92. </tr>
  93. </table>
  94. </s:form>
  95. <tableclass="pn-ltable"width="100%"cellspacing="1"cellpadding="0"
  96. border="0">
  97. <theadclass="pn-lthead">
  98. <tr>
  99. <th>
  100. 序号
  101. </th>
  102. <th>
  103. 文件名
  104. </th>
  105. <th>
  106. 上传时间
  107. </th>
  108. </tr>
  109. </thead>
  110. <tbodyclass="pn-ltbody">
  111. <tronmouseover="Pn.LTable.lineOver(this);"
  112. onmouseout="Pn.LTable.lineOut(this);"
  113. onclick="Pn.LTable.lineSelect(this);">
  114. <td>
  115. </td>
  116. <td>
  117. </td>
  118. <td>
  119. </td>
  120. </tr>
  121. </tbody>
  122. </table>
  123. </div>
  124. </body>
  125. </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.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后台处理上传文件:
Java代码 复制代码
  1. //uploadFile对应页面<inputtype="file"name="uploadFile">
  2. privateList<File>uploadFile;
  3. //文件名对应uploadFile+“FileName”,要不获取不到文件名
  4. privateList<String>uploadFileFileName;
  5. //文件上传
  6. publicStringmUploadFile(){
  7. if(null==uploadFile){
  8. this.addActionError("请上传文件!");
  9. }else{
  10. StringfileName="";
  11. try{
  12. //在自己代码中控制文件上传的服务器目录
  13. Stringdirectory=ServletActionContext.getServletContext().getRealPath("/uploads");
  14. //判断该目录是否存在,不存在则创建
  15. FileUtil.makeDir(directory);
  16. //循环处理上传的文件
  17. for(inti=0,j=uploadFile.size();i<j;i++){
  18. fileName=uploadFileFileName.get(i);
  19. StringfilePath=directory+File.separator+fileName;
  20. FileUtil.uploadFile(uploadFile.get(i),newFile(filePath));
  21. }
  22. }catch(IOExceptione){
  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. publicclassFileUtil{
  2. privatestaticfinalintBUFFER_SIZE=16*1024;
  3. publicstaticvoiduploadFile(Filesrc,Filedst)throwsIOException{
  4. InputStreamin=null;
  5. OutputStreamout=null;
  6. try{
  7. in=newBufferedInputStream(newFileInputStream(src),BUFFER_SIZE);
  8. out=newBufferedOutputStream(newFileOutputStream(dst),
  9. BUFFER_SIZE);
  10. byte[]buffer=newbyte[BUFFER_SIZE];
  11. while(in.read(buffer)>0){
  12. out.write(buffer);
  13. }
  14. }finally{
  15. if(null!=in){
  16. in.close();
  17. }
  18. if(null!=out){
  19. out.close();
  20. }
  21. }
  22. }
  23. publicstaticStringgetExtention(StringfileName){
  24. intpos=fileName.lastIndexOf(".");
  25. returnfileName.substring(pos);
  26. }
  27. publicstaticvoidmakeDir(Stringdirectory){
  28. Filedir=newFile(directory);
  29. if(!dir.isDirectory()){
  30. dir.mkdirs();
  31. }
  32. }
  33. publicstaticStringgenerateFileName(StringfileName)
  34. throwsUnsupportedEncodingException{
  35. DateFormatformat=newSimpleDateFormat("yyMMddHHmmss");
  36. StringformatDate=format.format(newDate());
  37. Stringextension=fileName.substring(fileName.lastIndexOf("."));
  38. fileName=newString(fileName.getBytes("iso8859-1"),"gb2312");
  39. returnfileName+"_"+formatDate+newRandom().nextInt(10000)
  40. +extension;
  41. }
  42. }
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文件;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值