实例:动态增加和删除上传文件的文本框
<%@ page language="java" import="java.util.*"pageEncoding="UTF-8"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Upload.jsp
<script type="text/javascript">
function addfile(){
var files = document.getElementById("files");
var input = document.createElement("input");
input.name="file";
input.type="file";
var delButton = document.createElement("input");
delButton.type="button";
delButton.value="删除";
delButton.οnclick=function del(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
var div = document.createElement("div");
div.appendChild(input);
div.appendChild(delButton);
files.appendChild(div);
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet" enctype="multipart/form-data" method="post">
上传用户<input type="text"name="username" /><br/>
文件1<input type="file" name="file1"/><br/>
文件2<input type="file" name="file2"/><br/>
<input type="submit" value="submit"/><br/>
</form>
<br/><br><hr/>
commons fileupload演示:<br/>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet2"enctype="multipart/form-data" method="post" >
上传用户<input type="text"name="username" /><br/>
文件1<input type="file"name="file1" /><br/>
文件2<input type="file"name="file2" /><br/>
<input type="submit"value="submit" /><br/>
</form>
<hr/>
<form action="${pageContext.request.contextPath }/servlet/UploadServlet2" enctype="multipart/form-data" method="post" >
<table>
<tr>
<td>
用户名:
</td>
<td>
<input type="text"name="username" >
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button"value="添加文件" οnclick="addfile()">
</td>
</tr>
<tr>
<td></td>
<td>
<div id="files"></div>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit"value="上传文件" >
</td>
</tr>
</table>
</form>
</body>
</html>
UploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException {
InputStream is=request.getInputStream();
byte[] buff=new byte[1024];
int len=0;
while((len=is.read(buff))>0){
System.out.println(new String(buff,0,len));
}
}