java組件commons-fileupload文件上傳示例
文件上傳在Web應(yīng)用中非常普遍,要在Java Web環(huán)境中實(shí)現(xiàn)文件上傳功能非常容易,因?yàn)榫W(wǎng)上已經(jīng)有許多用Java開(kāi)發(fā)的組件用于文件上傳,本文以使用最普遍的commons-fileupload組件為例,演示如何為Java Web應(yīng)用添加文件上傳功能。

commons-fileupload組件是Apache的一個(gè)開(kāi)源項(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中,文件名通過(guò)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,否則,拋出異常。如果上傳的文件大小超過(guò)了我們?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)文件上傳、下載、在線打開(kāi)
- 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)文章
Java設(shè)計(jì)模式之命令模式(Command模式)介紹
這篇文章主要介紹了Java設(shè)計(jì)模式之命令模式(Command模式)介紹,本文講解了Command模式的定義、如何使用命令模式等內(nèi)容,需要的朋友可以參考下2015-03-03
springboot bean循環(huán)依賴實(shí)現(xiàn)以及源碼分析
最近在使用Springboot做項(xiàng)目的時(shí)候,遇到了一個(gè)循環(huán)依賴的 問(wèn)題,所以下面這篇文章主要給大家介紹了關(guān)于springboot bean循環(huán)依賴實(shí)現(xiàn)以及源碼分析的相關(guān)資料,需要的朋友可以參考下2021-06-06
Java實(shí)現(xiàn)單鏈表翻轉(zhuǎn)實(shí)例代碼
Java實(shí)現(xiàn)單鏈表反轉(zhuǎn),遞歸和非遞歸兩種形式。接下來(lái)通過(guò)本文給大家分享Java實(shí)現(xiàn)單鏈表翻轉(zhuǎn)實(shí)例代碼,需要的的朋友參考下2017-03-03
web中拖拽排序和java后臺(tái)交互實(shí)現(xiàn)方法示例
這篇文章主要給大家介紹了關(guān)于web中拖拽排序和java后臺(tái)交互實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12
純Java實(shí)現(xiàn)數(shù)字證書生成簽名的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇純Java實(shí)現(xiàn)數(shù)字證書生成簽名的簡(jiǎn)單實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-08-08
Java線程池配置的一些常見(jiàn)誤區(qū)總結(jié)
這篇文章主要給大家介紹了關(guān)于Java線程池配置的一些常見(jiàn)誤區(qū),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
java常用工具類 XML工具類、數(shù)據(jù)驗(yàn)證工具類
這篇文章主要為大家詳細(xì)介紹了java常用工具類,包括XML工具類、數(shù)據(jù)驗(yàn)證工具類,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
Idea?編譯并運(yùn)行?Spark?3.1.1?源碼的方法
這篇文章主要介紹了Idea?編譯并運(yùn)行?Spark?3.1.1源碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11

