文件上傳在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:
@Overrideprotected 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()方法中初始化:
@Overridepublic 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。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答