標籤:eth out final action multipart 強制 方法 enc nal
public class Ticket{ private String customerName; private String subject; private String body; private Map<String, Attachment> attachments = new LinkedHashMap<>(); //...}
public class Attachment{ private String name; private byte[] contents; //...}
@WebServlet( name = "ticketServlet", urlPatterns = {"/tickets"}, loadOnStartup = 1)@MultipartConfig( fileSizeThreshold = 5_242_880, //5MB maxFileSize = 20_971_520L, //20MB maxRequestSize = 41_943_040L //40MB)//@MultipartConfig的location告訴瀏覽器應該在哪裡儲存臨時檔案(這裡未使用,讓應用伺服器使用它的預設臨時目錄即可)//fileSizeThreshold將告訴Web容器檔案必須達到多大才能寫入到臨時目錄中(在本例中,小於5MB的上傳檔案將儲存在記憶體中。)//在本例中,maxFileSize設定將禁止上傳大小超過20MB的檔案。//在本例中,maxRequestSize設定禁止大小超過40MB的請求。public class TicketServlet extends HttpServlet{ //...}
public class TicketServlet extends HttpServlet{ //... //downloadAttachment方法用於處理用戶端瀏覽器的下載請求。 private void downloadAttachment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //... //響應中設定的頭Content-Disposition,將強制瀏覽器詢問客戶是 //儲存還是下載檔案,而不是在瀏覽器中線上開啟該檔案。 response.setHeader("Content-Disposition", "attachment; filename=" + attachment.getName()); response.setContentType("application/octet-stream"); //使用ServletOutputStream將檔案內容輸出到響應中(對大檔案處理存在記憶體問題) ServletOutputStream stream = response.getOutputStream(); stream.write(attachment.getContents()); } //...}
public class TicketServlet extends HttpServlet{ //... private void createTicket(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Ticket ticket = new Ticket(); ticket.setCustomerName(request.getParameter("customerName")); ticket.setSubject(request.getParameter("subject")); ticket.setBody(request.getParameter("body")); Part filePart = request.getPart("file1"); if(filePart != null && filePart.getSize() > 0) { Attachment attachment = this.processAttachment(filePart); if(attachment != null) ticket.addAttachment(attachment); } int id; synchronized(this) { id = this.TICKET_ID_SEQUENCE++; this.ticketDatabase.put(id, ticket); } response.sendRedirect("tickets?action=view&ticketId=" + id); } private Attachment processAttachment(Part filePart) throws IOException { //從multipart請求中獲得InputStream,並將它複製到Attachment對象中。 InputStream inputStream = filePart.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int read; final byte[] bytes = new byte[1024]; while((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } Attachment attachment = new Attachment(); attachment.setName(filePart.getSubmittedFileName()); attachment.setContents(outputStream.toByteArray()); return attachment; } //...}
文章的源碼連結:https://pan.baidu.com/s/1ZnkwhlZo6_ihutdbgA7FvQ 密碼:q33p
其他關於檔案上傳的源碼連結:https://pan.baidu.com/s/1PW-sdelXD6i3S3deFmVi0g 密碼:v7hd
《Java Web進階編程》範例程式碼的:http://www.wrox.com/go/projavaforwebapps
參考:《Java Web進階編程》第3章 第6節
Java EE之通過表單上傳檔案