- 使用Servlet3.0實現文件上傳,不須要藉助第三方的jar包。
html
一、在index.jsp文件中編寫文件上傳的表單:
java
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Insert title here</title> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> </head> <body> <form action="${pageContext.request.contextPath }/uploadServlet" method="POST" enctype="multipart/form-data"> 文件:<input type="file" name="photo" /> <br> <input type="submit" value="上傳" /> </form> </body> </html>
二、須要在對應的自定義Servlet類中添加相應代碼:web
package com.geeklicreed.servlet; import java.io.IOException; 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; @WebServlet("/uploadServlet") @MultipartConfig // 代表當前Servlet能夠處理Multipart請求 public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取服務器保存上傳文件的目錄路徑 String path = this.getServletContext().getRealPath("images"); System.out.println(path); // 從請求中獲取Multipart請求中的上傳文件「部分」 Part part = request.getPart("photo"); //獲取指定的頭部屬性 String header = part.getHeader("Content-Disposition"); System.out.println(header); int index = header.lastIndexOf("="); String fileName = header.substring(index + 2, header.length() - 1); System.out.println(fileName); fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); System.out.println(fileName); // 完成文件上傳 part.write(path + "/" + fileName); /* 我電腦中的輸出結果爲: C:\Users\Administrator\Workspaces\MyEclipse 2016 CI\.metadata\.me_tcat7\webapps\fileUpload\images form-data; name="photo"; filename="C:\Users\Administrator\Desktop\魔術格言.txt" C:\Users\Administrator\Desktop\魔術格言.txt 魔術格言.txt */ } }
- 代碼解析:
瀏覽器
- javax.servlet.http.HttpServletRequest接口中的getPart(java.lang.String name)方法用於獲取給定名稱的Part對象:(即用<input type="file" name="photo"/>表單組件中的name屬性來獲取Part對象)tomcat
- javax.servlet.http.Part接口:服務器
- 這個接口表明用於接收multipart/form-data POST請求的部分或者單項。(只用於Serlvet3.0)
app
This class represents a part or form item that was received within a multipart/form-data POST request. Since: Servlet 3.0
- 該接口中主要用到的方法爲:
webapp
- getHeader(java.lang.String name)方法:獲取指定名稱的請求頭部信息,做爲字符串返回。jsp
- write(java.lang.String fileName)方法:一個便捷的方法用於將上傳的文件寫入硬盤中。ide
三、在myEclipse自帶的瀏覽器中訪問index.jsp頁面。能夠看到,在運行的tomcat對應的硬盤目錄中已經上傳:
- 附加說明:
- 在myEclipse中,默認會把Web項目放到Eclipse的工做空間下的.metadata\.me_tcat7\webapps。(在myEclipse中指定服務器爲tomcat7)