JSP上傳檔案到伺服器的範例
1.需要一個html檔案
upload.html(內容如下)
代碼如下 |
複製代碼 |
<html> <head> <title>Upload</title> </head> <body> <form action="HandleUpload" method="post" enctype="multipart/form-data"> <input id="file" name="file" type="file"> <input type="submit"> </form> </body> </html> |
2.建立一個servlet來處理前台傳過來的檔案,這個檔案放在org.Rudiment.lab下面名稱為 upload
代碼如下 |
複製代碼 |
package org.Rudiment.lab;
import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; 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,這個是servlet 3.0 新增加的特性,其它的,可以去api查詢 javax.servlet.annotation */ @WebServlet(name="upload", urlPatterns={"/Handleupload"}) /*這個是配置這個servlet用於處理位元據,與前台的 enctype="multipart/form-data" 對應*/ @MultipartConfig public class upload extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { /*設定響應產生的內容編碼*/ response.setContentType("text/html;charset=GBK"); /*擷取輸出資料流*/ PrintWriter out = response.getWriter(); try { /*這個是上傳的核心類*/ Part part = request.getPart("file"); /*通過part可以擷取到上傳的檔案的類型*/ out.println("上傳的類型:" + part.getContentType() + "<br />"); /*擷取上傳檔案大小*/ out.println("上傳的檔案大小:" + part.getSize() + "<br />"); /*擷取頭資訊*/ Collection<String> headerNames = part.getHeaderNames(); /*遍曆列印頭資訊*/ for(String headerName : headerNames) { out.println(headerName + "-------->" + part.getHeader(headerName) + "<br />"); } /*將上傳檔案上傳到應用/uploadFiles,如果沒有這個目錄要先建立*/ part.write(getServletContext().getRealPath("/uploadFiles") + "/" + System.currentTimeMillis()/1000); } catch (ServletException e) { e.printStackTrace(); } } } |
上面這個格式是採用注釋的方式 Annotation 進行配置servlet
如果要用web.xml 需要將
@WebServlet(name="upload", urlPatterns={"/Handleupload"})
@MultipartConfig
去掉,然後在web.xml中配置servlet
以上面這個為例子在web.xml中設定檔內容如下:
代碼如下 |
複製代碼 |
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>upload</servlet-name> <servlet-class>org.Rudiment.lab.upload</servlet-class> <multipart-config> </multipart-config> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/Handleupload</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>upload.html</welcome-file> </welcome-file-list> </web-app> |