Java EE之通過表單上傳檔案

來源:互聯網
上載者:User

標籤: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之通過表單上傳檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.