Servlet3.0檔案上傳
阿新 • • 發佈:2019-02-06
package upload; 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; @WebServlet(urlPatterns={"/upload.do"}) //這個註解是可以配置資訊的,比如檔案臨時存放目錄,檔案大小等等 @MultipartConfig() public class uploadServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Part part = req.getPart("Image"); String fileName = getName(part); PrintWriter printWriter = null; printWriter = resp.getWriter(); if(fileName==null){ printWriter.println("
請上傳有效的檔案
"); printWriter.flush(); }else{ //通過判斷限制檔案上傳的格式 if(!"png".equalsIgnoreCase(fileName.substring(fileName.indexOf('.')+1))){ printWriter.println("只允許PNG檔案
"); printWriter.flush(); return; } String path = req.getServletContext().getRealPath(("/File/"+fileName)); part.write(path); printWriter.println("檔名:"+fileName+"
檔案大小:"+part.getSize()+"
"); printWriter.flush(); } if(printWriter!=null){ printWriter.close(); } } private String getName(Part part){ String name = null; String ct = part.getContentType(); if(part==null) return name; if(ct==null) return name ;//當執行檔案上傳的時候,ContentType不為空 String disposition = part.getHeader("content-disposition"); String[] elements = disposition.split(";"); for(String ele:elements){ if(ele.trim().startsWith("filename")){ name = ele.substring(ele.indexOf('=')+1).trim().replace("\"", ""); return name; }else{ continue; } } return name; } }