servlet3.0利用自帶的Part來實現文件上傳 html
1,新建一個上傳文件的頁面upload.jsp java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> upload上傳文件(servlet)<br> <form name="fileupform" enctype="multipart/form-data" method="post" action="UploadServlet"> <input type="file" name="file"> <input type="text" id="name" name="name"/> <input type="submit" value="提交"/> </form> </body> </html>
2.再建一個上傳的servlet(UploadServlet) jsp
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; /** * Servlet implementation class uploadServlet */ @WebServlet("/UploadServlet") @MultipartConfig public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<h3>請使用post方式上傳</h3>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); Part part = request.getPart("file"); String header = part.getHeader("content-disposition"); String submittedFileName = part.getSubmittedFileName(); String fileName = header.substring(header.lastIndexOf("\\")+1,header.lastIndexOf("\"")); part.write(getServletContext().getRealPath("/upload/") + fileName); PrintWriter out = response.getWriter(); out.println("head:content-disposition: " + header + "<br>"); out.println("fileName: " +fileName + "<br>"); out.println("submittedFileName: " + submittedFileName + "<br>"); out.println(part.getName() + "<br>"); out.println("此文件的大小:"+part.getSize()+"<br />"); out.println("此文件類型:"+part.getContentType()+"<br />"); out.println("文本框內容:"+request.getParameter("name")+"<br />"); } }
3,而後運行結果出圖: post
上傳頁面: ui
執行頁面: spa
上傳後的文件位置: code
part.write這個地方能夠直接寫入到系統的某個位置。 orm