java組件commons-fileupload文件上傳示例。本站提示廣大學習愛好者:(java組件commons-fileupload文件上傳示例)文章只能為提供參考,不一定能成為您想要的結果。以下是java組件commons-fileupload文件上傳示例正文
文件上傳在Web運用中異常廣泛,要在Java Web情況中完成文件上傳功效異常輕易,由於網上曾經有很多用Java開辟的組件用於文件上傳,本文以應用最廣泛的commons-fileupload組件為例,演示若何為Java Web運用添加文件上傳功效。
commons-fileupload組件是Apache的一個開源項目之一,可以從http://commons.apache.org/fileupload/下載。該組件簡略易用,可完成一次上傳一個或多個文件,並可限制文件年夜小。
下載後解壓zip包,將commons-fileupload-1.x.jar復制到tomcat的webapps/你的webapp/WEB-INF/lib/下,假如目次不存在請自建目次。
新建一個UploadServlet.java用於文件上傳:
package com.liaoxuefeng.web; public class FileUploadServlet extends HttpServlet { private String uploadDir = "C:\\temp"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO: } }
當servlet收到閱讀器收回的Post要求後,在doPost()辦法中完成文件上傳,我們須要遍歷FileItemIterator,取得每個FileItemStream:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { ServletFileUpload upload = new ServletFileUpload(); // set max file size to 1 MB: upload.setFileSizeMax(1024 * 1024); FileItemIterator it = upload.getItemIterator(req); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (! item.isFormField()) { // it is a file upload: handleFileItem(item); } } req.getRequestDispatcher("success.jsp").forward(req, resp); } catch(FileUploadException e) { throw new ServletException("Cannot upload file.", e); } }
在handleFileItem()辦法中讀取上傳文件的輸出流,然後寫入到uploadDir中,文件名經由過程UUID隨機生成:
void handleFileItem(FileItemStream item) throws IOException { System.out.println("upload file: " + item.getName()); File newUploadFile = new File(uploadDir + "/" + UUID.randomUUID().toString()); byte[] buffer = new byte[4096]; InputStream input = null; OutputStream output = null; try { input = item.openStream(); output = new BufferedOutputStream(new FileOutputStream(newUploadFile)); for (;;) { int n = input.read(buffer); if (n==(-1)) break; output.write(buffer, 0, n); } } finally { if (input!=null) { try { input.close(); } catch (IOException e) {} } if (output!=null) { try { output.close(); } catch (IOException e) {} } } }
假如要在web.xml設置裝備擺設文件中讀取指定的上傳文件夾,可以在init()辦法中初始化:
@Override public void init(ServletConfig config) throws ServletException { super.init(config); this.uploaddir = config.getInitParameter("dir"); }
最初在web.xml中設置裝備擺設Servlet:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.liaoxuefeng.web.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping> </web-app>
設置裝備擺設好Servlet後,啟動Tomcat或Resin,寫一個簡略的index.htm測試:
<html> <body> <p>FileUploadServlet Demo</p> <form name="form1" action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" name="button" value="Submit" /> </form> </body> </html>
留意action="upload"指定了處置上傳文件的FileUploadServlet的映照URL。
當上傳勝利後,顯示success.jsp,不然,拋出異常。假如上傳的文件年夜小跨越了我們設定的1MB,就會獲得一個FileSizeLimitExceededException。
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。