使用Servlet實現上傳檔案功能

來源:互聯網
上載者:User

標籤:表單   span   location   style   cti   path   alt   ram   finally   

1.servlet只需加上一個注釋和用request.getPart來擷取檔案的值,這是servlet3.0的API

2.表單需要加上一個屬性enctype="multipart/form-data"

 

現在附上代碼

表單:

 <form method="POST" action="upload" enctype="multipart/form-data" >            File:            <input type="file" name="file" id="file" /> <br/>            Destination:            <input type="text" value="f:" name="destination"/>            <br/>            <input type="submit" value="Upload" name="upload" id="upload" />
</form>

 

servlet:

在類的聲名上加上這兩個注釋

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig

自訂的方法:

processRequest方法是擷取檔案的值的

protected void processRequest(HttpServletRequest request,            HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html;charset=UTF-8");
      request.setCharacterEncoding("utf-8");
      
     //擷取路徑 final String path = request.getParameter("destination");
     //擷取檔案的值 final Part filePart = request.getPart("file"); System.out.println(filePart); final String fileName = getFileName(filePart);     //使用IO流對檔案進行操作 OutputStream out = null; InputStream filecontent = null; final PrintWriter writer = response.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } writer.println("New file " + fileName + " created at " + path); LOGGER.log(Level.INFO, "File {0} being uploaded to {1}", new Object[]{fileName, path}); } catch (FileNotFoundException fne) { writer.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); writer.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[]{fne.getMessage()}); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } if (writer != null) { writer.close(); } } }

 

getFileName方法是擷取檔案名稱的

private String getFileName(final Part part) {final String partHeader = part.getHeader("content-disposition");LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);for (String content : part.getHeader("content-disposition").split(";")) {if (content.trim().startsWith("filename")) {return content.substring(content.indexOf(‘=‘) + 1).trim().replace("\"", "");}}return null;}

 

最後在doPost方法裡寫

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {processRequest(request, response);}

到這裡就全部完成了,長傳成功的效果,

 

使用Servlet實現上傳檔案功能

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.