java組件commons-fileupload文件上傳示例
文件上傳在Web應(yīng)用中非常普遍,要在Java Web環(huán)境中實(shí)現(xiàn)文件上傳功能非常容易,因?yàn)榫W(wǎng)上已經(jīng)有許多用Java開發(fā)的組件用于文件上傳,本文以使用最普遍的commons-fileupload組件為例,演示如何為Java Web應(yīng)用添加文件上傳功能。
commons-fileupload組件是Apache的一個(gè)開源項(xiàng)目之一,可以從http://commons.apache.org/fileupload/下載。該組件簡(jiǎn)單易用,可實(shí)現(xiàn)一次上傳一個(gè)或多個(gè)文件,并可限制文件大小。
下載后解壓zip包,將commons-fileupload-1.x.jar復(fù)制到tomcat的webapps/你的webapp/WEB-INF/lib/下,如果目錄不存在請(qǐng)自建目錄。
新建一個(gè)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: } }
當(dāng)servlet收到瀏覽器發(fā)出的Post請(qǐng)求后,在doPost()方法中實(shí)現(xiàn)文件上傳,我們需要遍歷FileItemIterator,獲得每一個(gè)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隨機(jī)生成:
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后,啟動(dòng)Tomcat或Resin,寫一個(gè)簡(jiǎn)單的index.htm測(cè)試:
<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。
當(dāng)上傳成功后,顯示success.jsp,否則,拋出異常。如果上傳的文件大小超過了我們?cè)O(shè)定的1MB,就會(huì)得到一個(gè)FileSizeLimitExceededException。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java組件SmartUpload和FileUpload實(shí)現(xiàn)文件上傳功能
- Java中使用fileupload組件實(shí)現(xiàn)文件上傳功能的實(shí)例代碼
- java使用common-fileupload實(shí)現(xiàn)文件上傳
- java組件commons-fileupload實(shí)現(xiàn)文件上傳、下載、在線打開
- Java組件commons fileupload實(shí)現(xiàn)文件上傳功能
- JavaEE組件commons-fileupload實(shí)現(xiàn)文件上傳、下載
- java組件fileupload文件上傳demo
- java組件commons-fileupload實(shí)現(xiàn)文件上傳
- JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析
- 使用fileupload組件實(shí)現(xiàn)文件上傳功能
相關(guān)文章
Spring線程池ThreadPoolTaskExecutor配置詳情
本篇文章主要介紹了Spring線程池ThreadPoolTaskExecutor配置詳情,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03SpringBoot使用validation-api實(shí)現(xiàn)對(duì)枚舉類參數(shù)校驗(yàn)的方法
這篇文章主要介紹了SpringBoot使用validation-api實(shí)現(xiàn)對(duì)枚舉類參數(shù)校驗(yàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11java如何接收和發(fā)送ASCII數(shù)據(jù)
這篇文章主要介紹了java如何接收和發(fā)送ASCII數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05java?Date獲取本月的開始時(shí)間與結(jié)束時(shí)間
這篇文章主要為大家介紹了java?Date獲取本月的開始時(shí)間與結(jié)束時(shí)間示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2023-05-05SpringBoot利用切面注解及反射實(shí)現(xiàn)事件監(jiān)聽功能
這篇文章主要介紹了springboot事件監(jiān)聽,通過利用切面、注解、反射實(shí)現(xiàn),接下來將對(duì)這幾種方式逐一說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2022-07-07