jsp Servlet 3.0文件上传
Servlet 3.0之前上传文件一般都要借助与第三方插件上传,有了servlet3.0后,上传文件从此变得简单。老规矩,直接上代码。
1、建立一个index.jsp用于表单提交
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="UploadServlet" method ="post" enctype="multipart/form-data"> 11 <input type="file" name="file"><br> 12 <input type="submit" value = "提交" name = "submit"> 13 </form> 14 </body> 15 </html>
2、用于上传文件的UploadServlet.java
1 package com.hs.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.MultipartConfig; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.servlet.http.Part; 13 14 /** 15 * Servlet implementation class UploadServlet 16 */ 17 @WebServlet("/UploadServlet") 18 @MultipartConfig(location = "D:\\")//文件上传的位置 19 public class UploadServlet extends HttpServlet { 20 private static final long serialVersionUID = 1L; 21 22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 23 this.doPost(request,response); 24 } 25 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 26 27 //上传文件对象 28 Part part = request.getPart("file"); 29 //将文件写到指定位置 30 part.write("shh.jpg"); 31 32 response.setCharacterEncoding("utf-8"); 33 PrintWriter out = response.getWriter(); 34 out.print("upload success"); 35 System.out.println("upload success"); 36 37 } 38 39 }
注:以上代码在servlet 3.0 tomcat7.0 测试可用。