Servlet實(shí)現(xiàn)文件上傳,可多文件上傳示例
一、Servlet實(shí)現(xiàn)文件上傳,需要添加第三方提供的jar包
下載地址:
1) commons-fileupload-1.2.2-bin.zip: 點(diǎn)擊打開鏈接
2) commons-io-2.3-bin.zip: 點(diǎn)擊打開鏈接
接著把這兩個(gè)jar包放到 lib文件夾下:

二:文件上傳的表單提交方式必須是POST方式,
編碼類型:enctype="multipart/form-data",默認(rèn)是 application/x-www-form-urlencoded
比如:
<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、舉例:
1.fileupload.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileuploadjsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
<!-- enctype 默認(rèn)是 application/x-www-form-urlencoded -->
<form action="FileUpLoad" enctype="multipart/form-data" method="post" >
用戶名:<input type="text" name="usename"> <br/>
上傳文件:<input type="file" name="file1"><br/>
上傳文件: <input type="file" name="file2"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.實(shí)際處理文件上傳的 FileUpLoad.java
package comservletfileupload;
import javaioFile;
import javaio*;
import javaioIOException;
import javaioPrintWriter;
import javautilList;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgapachecommonsfileuploadFileItem;
import orgapachecommonsfileuploadFileUploadException;
import orgapachecommonsfileuploaddiskDiskFileItemFactory;
import orgapachecommonsfileuploadservletServletFileUpload;
/**
*
* @author Administrator
* 文件上傳
* 具體步驟:
* 1)獲得磁盤文件條目工廠 DiskFileItemFactory 要導(dǎo)包
* 2) 利用 request 獲取 真實(shí)路徑 ,供臨時(shí)文件存儲(chǔ),和 最終文件存儲(chǔ) ,這兩個(gè)存儲(chǔ)位置可不同,也可相同
* 3)對(duì) DiskFileItemFactory 對(duì)象設(shè)置一些 屬性
* 4)高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory);
* 目的是調(diào)用 parseRequest(request)方法 獲得 FileItem 集合list ,
*
* 5)在 FileItem 對(duì)象中 獲取信息, 遍歷, 判斷 表單提交過來的信息 是否是 普通文本信息 另做處理
* 6)
* 第一種 用第三方 提供的 itemwrite( new File(path,filename) ); 直接寫到磁盤上
* 第二種 手動(dòng)處理
*
*/
public class FileUpLoad extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestsetCharacterEncoding("utf-8"); //設(shè)置編碼
//獲得磁盤文件條目工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//獲取文件需要上傳到的路徑
String path = requestgetRealPath("/upload");
//如果沒以下兩行設(shè)置的話,上傳大的 文件 會(huì)占用 很多內(nèi)存,
//設(shè)置暫時(shí)存放的 存儲(chǔ)室 , 這個(gè)存儲(chǔ)室,可以和 最終存儲(chǔ)文件 的目錄不同
/**
* 原理 它是先存到 暫時(shí)存儲(chǔ)室,然后在真正寫到 對(duì)應(yīng)目錄的硬盤上,
* 按理來說 當(dāng)上傳一個(gè)文件時(shí),其實(shí)是上傳了兩份,第一個(gè)是以 tem 格式的
* 然后再將其真正寫到 對(duì)應(yīng)目錄的硬盤上
*/
factorysetRepository(new File(path));
//設(shè)置 緩存的大小,當(dāng)上傳文件的容量超過該緩存時(shí),直接放到 暫時(shí)存儲(chǔ)室
factorysetSizeThreshold(1024*1024) ;
//高水平的API文件上傳處理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上傳多個(gè)文件
List<FileItem> list = (List<FileItem>)uploadparseRequest(request);
for(FileItem item : list)
{
//獲取表單的屬性名字
String name = itemgetFieldName();
//如果獲取的 表單信息是普通的 文本 信息
if(itemisFormField())
{
//獲取用戶具體輸入的字符串 ,名字起得挺好,因?yàn)楸韱翁峤贿^來的是 字符串類型的
String value = itemgetString() ;
requestsetAttribute(name, value);
}
//對(duì)傳入的非 簡(jiǎn)單的字符串進(jìn)行處理 ,比如說二進(jìn)制的 圖片,電影這些
else
{
/**
* 以下三步,主要獲取 上傳文件的名字
*/
//獲取路徑名
String value = itemgetName() ;
//索引到最后一個(gè)反斜杠
int start = valuelastIndexOf("\\");
//截取 上傳文件的 字符串名字,加1是 去掉反斜杠,
String filename = valuesubstring(start+1);
requestsetAttribute(name, filename);
//真正寫到磁盤上
//它拋出的異常 用exception 捕捉
//itemwrite( new File(path,filename) );//第三方提供的
//手動(dòng)寫的
OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = itemgetInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
Systemoutprintln("獲取上傳文件的總共的容量:"+itemgetSize());
// inread(buf) 每次讀到的數(shù)據(jù)存放在 buf 數(shù)組中
while( (length = inread(buf) ) != -1)
{
//在 buf 數(shù)組中 取出數(shù)據(jù) 寫到 (輸出流)磁盤上
outwrite(buf, 0, length);
}
inclose();
outclose();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
//eprintStackTrace();
}
requestgetRequestDispatcher("filedemojsp")forward(request, response);
}
}
System.out.println("獲取上傳文件的總共的容量:"+item.getSize());
3.filedemo.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'filedemojsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
用戶名:${requestScopeusename } <br/>
文件:${requestScopefile1 }<br/>
${requestScopefile2 }<br/>
<!-- 把上傳的圖片顯示出來 -->
<img alt="go" src="upload/<%=(String)requestgetAttribute("file1")%> " />
</body>
</html>
4結(jié)果頁面:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java Servlet簡(jiǎn)單實(shí)例分享(文件上傳下載demo)
- SpringMVC + servlet3.0 文件上傳的配置和實(shí)現(xiàn)代碼
- Servlet實(shí)現(xiàn)多文件上傳功能
- Servlet3.0實(shí)現(xiàn)文件上傳的方法
- servlet+jquery實(shí)現(xiàn)文件上傳進(jìn)度條示例代碼
- java基于servlet使用組件smartUpload實(shí)現(xiàn)文件上傳
- java基于servlet實(shí)現(xiàn)文件上傳功能解析
- servlet+JSP+mysql實(shí)現(xiàn)文件上傳的方法
- Android中發(fā)送Http請(qǐng)求(包括文件上傳、servlet接收)的實(shí)例代碼
- Servlet實(shí)現(xiàn)簡(jiǎn)單文件上傳功能
相關(guān)文章
js抽獎(jiǎng)實(shí)現(xiàn)隨機(jī)抽獎(jiǎng)代碼效果
這篇文章主要介紹了js隨機(jī)抽獎(jiǎng)代碼效果,大家參考使用2013-12-12
uni-app實(shí)現(xiàn)數(shù)據(jù)上拉加載更多功能實(shí)例
數(shù)據(jù)列表在很多時(shí)候,經(jīng)常會(huì)用到,下面這篇文章主要給大家介紹了關(guān)于uni-app實(shí)現(xiàn)數(shù)據(jù)上拉加載更多功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
webpack實(shí)現(xiàn)熱加載自動(dòng)刷新的方法
本文介紹了webpack實(shí)現(xiàn)熱加載自動(dòng)刷新的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
JS正則表達(dá)式大全(整理詳細(xì)且實(shí)用)
JS正則表達(dá)式大全(整理詳細(xì)且實(shí)用)。需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-11-11
Javascript面試經(jīng)典套路reduce函數(shù)查重
reduce函數(shù),是ECMAScript5規(guī)范中出現(xiàn)的數(shù)組方法.下面通過本文給大家分享Javascript面試經(jīng)典套路reduce函數(shù)查重,需要的朋友參考下吧2017-03-03
Javascript點(diǎn)擊其他任意地方隱藏關(guān)閉DIV實(shí)例
這篇文章主要分享一個(gè)Javascript點(diǎn)擊其他任意地方隱藏關(guān)閉DIV實(shí)例,需要的朋友可以參考下。2016-06-06
JavaScript數(shù)組去重的3種方法和代碼實(shí)例
這篇文章主要介紹了JavaScript數(shù)組去重的3種方法和代碼實(shí)例,本文直接給出實(shí)例代碼,需要的朋友可以參考下2015-07-07
JS中使用 after 偽類清除浮動(dòng)實(shí)例
這篇文章主要介紹了使用 after 偽類清除浮動(dòng)實(shí)例,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下2017-03-03

