Apache Commons fileUpload文件上傳多個示例分享
本文通過實例來介紹如何使用commons-fileupload.jar,Apache的commons-fileupload.jar可方便的實現(xiàn)文件的上傳功能,具體內(nèi)容如下
將Apache的commons-fileupload.jar放在應(yīng)用程序的WEB-INF\lib下,即可使用。下面舉例介紹如何使用它的文件上傳功能。
所使用的fileUpload版本為1.2,環(huán)境為Eclipse3.3+MyEclipse6.0。FileUpload 是基于 Commons IO的,所以在進(jìn)入項目前先確定Commons IO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。
此文作示例工程可在文章最后的附件中下載。
示例1
最簡單的例子,通過ServletFileUpload靜態(tài)類來解析Request,工廠類FileItemFactory會對mulipart類的表單中的所有字段進(jìn)行處理,不只是file字段。getName()得到文件名,getString()得到表單數(shù)據(jù)內(nèi)容,isFormField()可判斷是否為普通的表單項。
demo1.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
//必須是multipart的表單數(shù)據(jù)。
<form name="myform" action="demo1.jsp" method="post"
enctype="multipart/form-data">
Your name: <br>
<input type="text" name="name" size="15"><br>
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo1.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//檢查輸入請求是否為multipart表單數(shù)據(jù)。
if (isMultipart == true) {
FileItemFactory factory = new DiskFileItemFactory();//為該請求創(chuàng)建一個DiskFileItemFactory對象,通過它來解析請求。執(zhí)行解析后,所有的表單項目都保存在一個List中。
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
//檢查當(dāng)前項目是普通表單項目還是上傳文件。
if (item.isFormField()) {//如果是普通表單項目,顯示表單內(nèi)容。
String fieldName = item.getFieldName();
if (fieldName.equals("name")) //對應(yīng)demo1.html中type="text" name="name"
out.print("the field name is" + item.getString());//顯示表單內(nèi)容。
out.print("<br>");
} else {//如果是上傳文件,顯示文件名。
out.print("the upload file name is" + item.getName());
out.print("<br>");
}
}
} else {
out.print("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
結(jié)果:
the field name isjeff
the upload file name isD:\C語言考試樣題\作業(yè)題.rar
示例2
上傳兩個文件到指定的目錄。
demo2.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo2.jsp" method="post"
enctype="multipart/form-data">
File1:<br>
<input type="file" name="myfile"><br>
File2:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo2.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String uploadPath="D:\\temp";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart==true){
try{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> itr = items.iterator();
while(itr.hasNext()){//依次處理每個文件
FileItem item=(FileItem)itr.next();
String fileName=item.getName();//獲得文件名,包括路徑
if(fileName!=null){
File fullFile=new File(item.getName());
File savedFile=new File(uploadPath,fullFile.getName());
item.write(savedFile);
}
}
out.print("upload succeed");
}
catch(Exception e){
e.printStackTrace();
}
}
else{
out.println("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
結(jié)果:
upload succeed
此時,在"D:\temp"下可以看到你上傳的兩個文件。
示例3
上傳一個文件到指定的目錄,并限定文件大小。
demo3.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo3.jsp" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo3.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
File uploadPath = new File("D:\\temp");//上傳文件目錄
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
// 臨時文件目錄
File tempPathFile = new File("d:\\temp\\buffer\\");
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 設(shè)置緩沖區(qū)大小,這里是4kb
factory.setRepository(tempPathFile);//設(shè)置緩沖區(qū)目錄
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 設(shè)置最大文件尺寸,這里是4MB
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile
.getName());
fi.write(savedFile);
}
}
out.print("upload succeed");
} catch (Exception e) {
e.printStackTrace();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
示例4
利用Servlet來實現(xiàn)文件上傳。
Upload.java
package com.zj.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
private String uploadPath = "D:\\temp"; // 上傳文件的目錄
private String tempPath = "d:\\temp\\buffer\\"; // 臨時文件目錄
File tempPathFile;
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 設(shè)置緩沖區(qū)大小,這里是4kb
factory.setRepository(tempPathFile);// 設(shè)置緩沖區(qū)目錄
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 設(shè)置最大文件尺寸,這里是4MB
List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
} catch (Exception e) {
// 可以跳轉(zhuǎn)出錯頁面
e.printStackTrace();
}
}
public void init() throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
demo4.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
// action="fileupload"對應(yīng)web.xml中<servlet-mapping>中<url-pattern>的設(shè)置.
<form name="myform" action="fileupload" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
web.xml
<servlet> <servlet-name>Upload</servlet-name> <servlet-class>com.zj.sample.Upload</servlet-class> </servlet> <servlet-mapping> <servlet-name>Upload</servlet-name> <url-pattern>/fileupload</url-pattern> </servlet-mapping>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java利用Apache commons codec進(jìn)行MD5加密,BASE64加密解密,執(zhí)行系統(tǒng)命令
- Apache Commons Math3探索之快速傅立葉變換代碼示例
- Apache Commons Math3探索之多項式曲線擬合實現(xiàn)代碼
- Apache Commons Math3學(xué)習(xí)之?dāng)?shù)值積分實例代碼
- Apache commons fileupload文件上傳實例講解
- Apache Commons fileUpload實現(xiàn)文件上傳之一
- Apache Commons DbUtils工具包使用介紹
- apache commons工具集代碼詳解
相關(guān)文章
java Beanutils.copyProperties( )用法詳解
這篇文章主要介紹了java Beanutils.copyProperties( )用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
SpringBoot優(yōu)雅的進(jìn)行全局異常處理的實現(xiàn)步驟
在軟件開發(fā)的世界里,異常處理是保證系統(tǒng)穩(wěn)定性和用戶體驗的關(guān)鍵因素之一,尤其是在構(gòu)建基于微服務(wù)架構(gòu)的應(yīng)用時,SpringBoot提供了一套強(qiáng)大的工具來幫助開發(fā)者管理這些異常,所以本文給大家介紹了SpringBoot如何優(yōu)雅的進(jìn)行全局異常處理,需要的朋友可以參考下2025-02-02
Java并發(fā)編程示例(六):等待線程執(zhí)行終止
這篇文章主要介紹了Java并發(fā)編程示例(六):等待線程執(zhí)行終止,在本節(jié),示例程序演示等待初始化方法完成后,再去執(zhí)行其他任務(wù),需要的朋友可以參考下2014-12-12
使用EasyPoi輕松導(dǎo)入導(dǎo)出Excel文檔的方法示例
這篇文章主要介紹了使用EasyPoi輕松導(dǎo)入導(dǎo)出Excel文檔的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Java的RocketMq水平擴(kuò)展及負(fù)載均衡詳解
這篇文章主要介紹了Java的RocketMq水平擴(kuò)展及負(fù)載均衡詳解,RocketMQ是一個分布式具有高度可擴(kuò)展性的消息中間件,本文旨在探索在broker端,生產(chǎn)端,以及消費(fèi)端是如何做到橫向擴(kuò)展以及負(fù)載均衡的,需要的朋友可以參考下2024-01-01

