国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java組件commons-fileupload文件上傳示例

2019-11-26 13:42:49
字體:
來源:轉載
供稿:網友

文件上傳在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。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿拉尔市| 苍南县| 个旧市| 长兴县| 河西区| 安龙县| 临湘市| 新竹市| 景德镇市| 宁阳县| 璧山县| 黄大仙区| 乌苏市| 中西区| 丘北县| 辽阳县| 石阡县| 鹿邑县| 含山县| 平阳县| 潮安县| 肥西县| 佛冈县| 永春县| 垫江县| 潮州市| 安塞县| 长白| 晋宁县| 达孜县| 海阳市| 梅河口市| 报价| 施秉县| 阿城市| 合江县| 武山县| 北安市| 奉化市| 进贤县| 江北区|