FileUpload
一upload原理:
1.表单的method必须是post方法
2.enctype属性必须是“mutipatr/form-data”类型
enctype默认的属性是“application/x-www-form-urlencoded”
enctype的作用是:告知服务器请求正文的MIME类型
application/x-www-form-urlencoded:username=aaa&password=123
ServletRequest.getParameter(String name),该方法是专门用来读取enctype是“application/x-www-form-urlencoded”时的方法
3.在Servlet里面通过request.getInputStream()方法就可以获得文件输入流
byte[] b= new byte[1024];
int len=0;
InputStream is = request.getInputStream();
while((len=is.read(b)) != -1){
System.out.println(new String(b,0 ,len));
}
代码示例
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data"> 11 请输入FileName<input type="text" name="FileName"/> 12 <input type="file"name="file"/> 13 <input type="submit" value="提交"/> 14 ${pageContext.request.contextPath} 15 16 17 18 19 </form> 20 21 </body> 22 </html>
1 package jcbc.ds.test1; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.commons.fileupload.FileItem; 13 import org.apache.commons.fileupload.FileUploadException; 14 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 15 import org.apache.commons.fileupload.servlet.ServletFileUpload; 16 17 /** 18 * Servlet implementation class UploadServlet 19 */ 20 public class UploadServlet extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public UploadServlet() { 27 super(); 28 29 } 30 31 /** 32 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 36 //创建DiskFileItemFactory对象 37 //DiskFileItemFactory dis = new DiskFileItemFactory(); 38 //创建ServletFileUpload对象 39 /*ServletFileUpload servletupload = new ServletFileUpload(dis);*/ 40 byte[] b= new byte[1024]; 41 int len=0; 42 InputStream is = request.getInputStream(); 43 while((len=is.read(b)) != -1){ 44 System.out.println(new String(b,0 ,len)); 45 } 46 /*try { 47 List<FileItem> fileItem = servletupload.parseRequest(request); 48 for(FileItem items : fileItem) { 49 System.out.println(items.getName()); 50 //进行解析传过来的数据进行封装 51 } 52 is.close(); 53 54 } catch (FileUploadException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 }*/ 58 59 } 60 61 }
二借助第三方组件实现文件上传:
步骤:
1.拷贝jar包commons-fileupload.jar commons-io.jar
具体参考http://commons.apache.org/proper/commons-fileupload/using.html
2.//创建DiskFileItemFactory对象
DiskFileItemFactory disfileitemfactory = new DiskFileItemFactory();
//创建ServletFileUpload对象
ServletFileUpload servletupload = new ServletFileUpload(disfileitemfactory);
3.获取封装信息
List<FileItem> fileItem = servletupload.parseRequest(request);//这里会抛异常
具体步骤代码如下:
1 package jcbc.ds.test1; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.util.List; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import org.apache.commons.fileupload.FileItem; 15 import org.apache.commons.fileupload.FileUploadException; 16 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 import org.apache.commons.io.FileUtils; 19 20 /** 21 * Servlet implementation class UploadServlet 22 */ 23 public class UploadServlet extends HttpServlet { 24 private static final long serialVersionUID = 1L; 25 26 /** 27 * @see HttpServlet#HttpServlet() 28 */ 29 public UploadServlet() { 30 super(); 31 32 } 33 34 /** 35 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 36 */ 37 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 38 response.setContentType("text/html; charset=gbk"); 39 //创建DiskFileItemFactory对象 40 DiskFileItemFactory disfileitemfactory = new DiskFileItemFactory(); 41 //创建ServletFileUpload对象 42 ServletFileUpload servletupload = new ServletFileUpload(disfileitemfactory); 43 44 try { 45 //封装 46 List<FileItem> fileItem = servletupload.parseRequest(request); 47 for(FileItem files : fileItem ){ 48 if(files.isFormField()){ 49 System.out.println(files.getFieldName()); 50 } 51 else{ 52 InputStream is = files.getInputStream(); 53 String name = files.getName(); 54 //截取文件名 55 String fileName = name.substring(name.lastIndexOf("\\")+1); 56 System.out.println(fileName);//打印结果为huxuebing.txt 57 58 System.out.println(request.getServletContext().getRealPath("/fileName")); 59 //创建File类对象 60 File file = new File(request.getServletContext().getRealPath("/")+fileName); 61 //判断该文件是否存在如果不存在就创建,存在就不创建 62 if(file.exists()==false){ 63 System.out.println("=================="); 64 file.createNewFile(); 65 System.out.println("=================="); 66 } 67 try { 68 //向创建的文件写入 69 files.write(file); 70 } catch (Exception e) { 71 // TODO Auto-generated catch block 72 e.printStackTrace(); 73 } 74 75 } 76 77 } 78 79 } catch (FileUploadException e) { 80 // TODO Auto-generated catch block 81 e.printStackTrace(); 82 } 83 84 } 85 86 }
FileName
huxuebing.txt
D:\workSpace\web2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\day18\fileName
==================
==================