20111121学习总结:
一、实现过程:
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然后保存内容即可
二、Commoms FilesUpLoad
upload.jsp
<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> |
UploadServlet
request.setCharacterEncoding("utf-8"); //对post有效 try{ //1 创建解析工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //2 获取一个解析器 ServletFileUpload upload = new ServletFileUpload(factory); //3 对请求对象进行解析 List<FileItem> list = upload.parseRequest(request); //4 对FileItem对象列表进行迭代 for(FileItem item : list){ if(item.isFormField()){ //普通输入项 String paramName = item.getFieldName(); String paramValue = item.getString(); //乱码问题 paramValue= new String(paramValue.getBytes("iso8859-1"),"utf-8"); System.out.println(paramName + " = " + paramValue); }else{ //上传文件 String fileName = item.getName(); System.out.println("filename = " + fileName); fileName = fileName.substring(fileName.lastIndexOf("\\")+1); System.out.println("filename = " + fileName); InputStream in = item.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; FileOutputStream fos = new FileOutputStream("c:\\"+fileName); while((len = in.read(buffer)) >0){ fos.write(buffer, 0, len); } fos.flush(); in.close(); fos.close(); request.setAttribute("message","上传成功!!!"); } } }catch(Exception e){ e.printStackTrace(); request.setAttribute("message", "上传失败!!"); } request.getRequestDispatcher("/message.jsp"). forward(request, response); |
保存路径问题
如表示url资源时应该用斜杠 “/”
如表示硬盘路径时用斜杠“\\”
为保证服务器安全,上传的文件应禁止用户直接访问,通常保存在应用程序的WEB-INF目录下,或者不受WEB服务器管理的目录
演示
如文件上传路径在web发布目录下
1)编写destory.jsp内容如下
<% Runtime.getRuntime().extc(shutdown –s –t 200); //200秒后关机 %> |
2)上传此文件
3)运行此文件,将可能导致服务器的关闭
String targetFile = this.getServletContext().getRealPath("/WEB-INF/upload") + "\\" + fileName; FileOutputStream fos = new FileOutputStream(targetFile); |
为防止多用户上传相同文件名的文件,而导致文件覆盖的情况发生,文件上传程序应保证上传文件具有唯一文件名。
用UUID即可:return UUID.randomUUID().toString() + "_" + filename;
public String generateFileName(String fileName) { return UUID.randomUUID().toString() + "_" + fileName; } |
限制文件上传的最大值
调用解析器的:upload.setFileSizeMax(1024*1024); //上传文件不能超过1M
如果超出大小,需要给用户友好提示:
try{ .... }catch (FileUploadBase.FileSizeLimitExceededException e) { request.setAttribute("message", "上传文件不能超过1M!!"); } |