1. 程式人生 > 其它 >21. Servlet3.0 / 3.1 檔案上傳 Plus

21. Servlet3.0 / 3.1 檔案上傳 Plus

Servlet3.0 提供了專門的檔案上傳 API

HttpServletRequest 的 getPart()方法可以完成單個檔案上傳而 getParts()方法可以完成多個檔案上傳。注意,這兩個方法是從 Servlet3.0 開始定義的。


getPart
方法:Part getPart(String name) throws IOException, ServletException
作用:獲取 Multipart 請求中指定名稱的”部分”。一般這裡的引數是上傳表單中的”file”表單項的 name 值。


getParts
方法:java.util.Collection getParts()throws IOException, ServletException
作用:獲取 Multipart 請求中的所有”部分”。多檔案上傳時使用該方法。

Servlet3.0在javax.servlet.http包中新增了Part介面,該介面中常用的方法有:


write
方法:void write(String fileName) throws IOException
作用:將上傳檔案資料寫入到指定的檔案中。

另外在Servlet3.1中的Part接口裡面新增了getSubmittedFileName方法用來獲取上傳的檔名

所以我們直接用3.1 反正你喜歡..

還有就是一個:@MultipartConfig // @MultipartConfig 表示當前servlet可以處理multipart請求 這個載入Servlet,加上吧 .... 複製即可

所以我們直接幹就完了:

package upload;

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("/upload") @MultipartConfig // @MultipartConfig 表示當前servlet可以處理multipart請求 這個加上吧 public class upload extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part part = request.getPart("img"); //Part 通過request 獲取, 引數是檔案域的name String path = this.getServletContext().getRealPath("/img"); String FileName = part.getSubmittedFileName(); //Servlet3.1才有的!!! //寫出到內個img資料夾中 part.write(path + "/" + FileName); //別粗心!!! 記得 + 斜槓 System.out.println(path); System.out.println(FileName); } }

自己看吧 我累了 拜拜.