1、 个文件a.txt b.txt
a.txt 内容:aaa
b.txt内容:bbb
2、 upload.jsp
<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> |
3、 UploadServlet
//如果表达enctype="multipart/form-data",则servlet中无法获得参数值,所以下面代码打印为null System.out.println(request.getParameter("username")); InputStream in = request.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len=in.read(buffer))>0){ System.out.println(new String(buffer)); } |
打印结果为
null -----------------------------7db109f106b4 Content-Disposition: form-data; name="username" ccc -----------------------------7db109f106b4 Content-Disposition: form-data; name="file1"; filename="C:\Documents and Settings\Administrator\妗岄潰\a.txt" Content-Type: text/plain aaaaaa aaaaaaaaa -----------------------------7db109f106b4 Content-Disposition: form-data; name="file2"; filename="C:\Documents and Settings\Administrator\妗岄潰\b.txt" Content-Type: text/plain bbbbbbbbbbb -----------------------------7db109f106b4-- |
因此,上传文件只需解析Content-Type:text/plain然后保存内容即可