java組件commons-fileupload文件上傳示例
文件上傳在Web應用中非常普遍,要在Java Web環(huán)境中實現(xiàn)文件上傳功能非常容易,因為網(wǎng)上已經(jīng)有許多用Java開發(fā)的組件用于文件上傳,本文以使用最普遍的commons-fileupload組件為例,演示如何為Java Web應用添加文件上傳功能。
commons-fileupload組件是Apache的一個開源項目之一,可以從http://commons.apache.org/fileupload/下載。該組件簡單易用,可實現(xiàn)一次上傳一個或多個文件,并可限制文件大小。
下載后解壓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收到瀏覽器發(fā)出的Post請求后,在doPost()方法中實現(xiàn)文件上傳,我們需要遍歷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。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- java組件SmartUpload和FileUpload實現(xiàn)文件上傳功能
- Java中使用fileupload組件實現(xiàn)文件上傳功能的實例代碼
- java使用common-fileupload實現(xiàn)文件上傳
- java組件commons-fileupload實現(xiàn)文件上傳、下載、在線打開
- Java組件commons fileupload實現(xiàn)文件上傳功能
- JavaEE組件commons-fileupload實現(xiàn)文件上傳、下載
- java組件fileupload文件上傳demo
- java組件commons-fileupload實現(xiàn)文件上傳
- JAVA使用commos-fileupload實現(xiàn)文件上傳與下載實例解析
- 使用fileupload組件實現(xiàn)文件上傳功能
相關(guān)文章
Spring線程池ThreadPoolTaskExecutor配置詳情
本篇文章主要介紹了Spring線程池ThreadPoolTaskExecutor配置詳情,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03SpringBoot使用validation-api實現(xiàn)對枚舉類參數(shù)校驗的方法
這篇文章主要介紹了SpringBoot使用validation-api實現(xiàn)對枚舉類參數(shù)校驗,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11java如何接收和發(fā)送ASCII數(shù)據(jù)
這篇文章主要介紹了java如何接收和發(fā)送ASCII數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09springboot中Getmapping獲取參數(shù)的實現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05SpringBoot利用切面注解及反射實現(xiàn)事件監(jiān)聽功能
這篇文章主要介紹了springboot事件監(jiān)聽,通過利用切面、注解、反射實現(xiàn),接下來將對這幾種方式逐一說明,具有很好的參考價值,希望對大家有所幫助2022-07-07