Servlet實(shí)現(xiàn)多文件上傳功能
一、Servlet實(shí)現(xiàn)文件上傳,需要添加第三方提供的jar包
下載地址:
1) commons-fileupload-1.2.2-bin.zip : 點(diǎn)擊打開(kāi)鏈接
2) commons-io-2.3-bin.zip : 點(diǎn)擊打開(kāi)鏈接
接著把這兩個(gè)jar包放到 lib文件夾下:
二、文件上傳的表單提交方式必須是POST方式
編碼類(lèi)型: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="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'fileupload.jsp' 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="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> <!-- enctype 默認(rèn)是 application/x-www-form-urlencoded --> <form action="FileUpLoad" enctype="multipart/form-data" method="post" > 用戶(hù)名:<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 com.servlet.fileupload; import java.io.File; import java.io.*; import java.io.IOException; import java.io.PrintWriter; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * * @author Administrator * 文件上傳 * 具體步驟: * 1)獲得磁盤(pán)文件條目工廠 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ì)象中 獲取信息, 遍歷, 判斷 表單提交過(guò)來(lái)的信息 是否是 普通文本信息 另做處理 * 6) * 第一種. 用第三方 提供的 item.write( new File(path,filename) ); 直接寫(xiě)到磁盤(pán)上 * 第二種. 手動(dòng)處理 * */ public class FileUpLoad extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //設(shè)置編碼 //獲得磁盤(pán)文件條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //獲取文件需要上傳到的路徑 String path = request.getRealPath("/upload"); //如果沒(méi)以下兩行設(shè)置的話(huà),上傳大的 文件 會(huì)占用 很多內(nèi)存, //設(shè)置暫時(shí)存放的 存儲(chǔ)室 , 這個(gè)存儲(chǔ)室,可以和 最終存儲(chǔ)文件 的目錄不同 /** * 原理 它是先存到 暫時(shí)存儲(chǔ)室,然后在真正寫(xiě)到 對(duì)應(yīng)目錄的硬盤(pán)上, * 按理來(lái)說(shuō) 當(dāng)上傳一個(gè)文件時(shí),其實(shí)是上傳了兩份,第一個(gè)是以 .tem 格式的 * 然后再將其真正寫(xiě)到 對(duì)應(yīng)目錄的硬盤(pán)上 */ factory.setRepository(new File(path)); //設(shè)置 緩存的大小,當(dāng)上傳文件的容量超過(guò)該緩存時(shí),直接放到 暫時(shí)存儲(chǔ)室 factory.setSizeThreshold(1024*1024) ; //高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); try { //可以上傳多個(gè)文件 List<FileItem> list = (List<FileItem>)upload.parseRequest(request); for(FileItem item : list) { //獲取表單的屬性名字 String name = item.getFieldName(); //如果獲取的 表單信息是普通的 文本 信息 if(item.isFormField()) { //獲取用戶(hù)具體輸入的字符串 ,名字起得挺好,因?yàn)楸韱翁峤贿^(guò)來(lái)的是 字符串類(lèi)型的 String value = item.getString() ; request.setAttribute(name, value); } //對(duì)傳入的非 簡(jiǎn)單的字符串進(jìn)行處理 ,比如說(shuō)二進(jìn)制的 圖片,電影這些 else { /** * 以下三步,主要獲取 上傳文件的名字 */ //獲取路徑名 String value = item.getName() ; //索引到最后一個(gè)反斜杠 int start = value.lastIndexOf("\\"); //截取 上傳文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start+1); request.setAttribute(name, filename); //真正寫(xiě)到磁盤(pán)上 //它拋出的異常 用exception 捕捉 //item.write( new File(path,filename) );//第三方提供的 //手動(dòng)寫(xiě)的 OutputStream out = new FileOutputStream(new File(path,filename)); InputStream in = item.getInputStream() ; int length = 0 ; byte [] buf = new byte[1024] ; System.out.println("獲取上傳文件的總共的容量:"+item.getSize()); // in.read(buf) 每次讀到的數(shù)據(jù)存放在 buf 數(shù)組中 while( (length = in.read(buf) ) != -1) { //在 buf 數(shù)組中 取出數(shù)據(jù) 寫(xiě)到 (輸出流)磁盤(pán)上 out.write(buf, 0, length); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } request.getRequestDispatcher("filedemo.jsp").forward(request, response); } }
System.out.println("獲取上傳文件的總共的容量:"+item.getSize());
3.filedemo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'filedemo.jsp' 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="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> 用戶(hù)名:${requestScope.usename } <br/> 文件:${requestScope.file1 }<br/> ${requestScope.file2 }<br/> <!-- 把上傳的圖片顯示出來(lái) --> <img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " /> </body> </html>
4.結(jié)果頁(yè)面
下載鏈接:
1)Struts2之下載 點(diǎn)擊打開(kāi)鏈接
2)Struts2之上傳 點(diǎn)擊打開(kāi)鏈接
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java Servlet簡(jiǎn)單實(shí)例分享(文件上傳下載demo)
- SpringMVC + servlet3.0 文件上傳的配置和實(shí)現(xiàn)代碼
- Servlet3.0實(shí)現(xiàn)文件上傳的方法
- servlet+jquery實(shí)現(xiàn)文件上傳進(jìn)度條示例代碼
- Servlet實(shí)現(xià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)文章
一文教你學(xué)會(huì)搭建SpringBoot分布式項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了搭建SpringBoot分布式項(xiàng)目的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01spring學(xué)習(xí)之參數(shù)傳遞與檢驗(yàn)詳解
這篇文章主要給大家介紹了關(guān)于spring參數(shù)傳遞與檢驗(yàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,需要的朋友們下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-07-07Java在PowerPoint幻燈片中創(chuàng)建散點(diǎn)圖的方法
散點(diǎn)圖是通過(guò)兩組數(shù)據(jù)構(gòu)成多個(gè)坐標(biāo)點(diǎn),考察坐標(biāo)點(diǎn)的分布,判斷兩變量之間是否存在某種關(guān)聯(lián)或總結(jié)坐標(biāo)點(diǎn)的分布模式,這篇文章主要介紹了Java如何在PowerPoint幻燈片中創(chuàng)建散點(diǎn)圖,需要的朋友可以參考下2023-04-04Java Scala泛型(泛型方法,泛型類(lèi),泛型特質(zhì),上下界,協(xié)變、逆變、非變)
泛型的意思是泛指某種具體的數(shù)據(jù)類(lèi)型, 在Scala中, 泛型用[數(shù)據(jù)類(lèi)型]表示. 在實(shí)際開(kāi)發(fā)中, 泛型一般是結(jié)合數(shù)組或者集合來(lái)使用的,這篇文章主要介紹了Scala泛型(泛型方法,泛型類(lèi),泛型特質(zhì),上下界,協(xié)變、逆變、非變),需要的朋友可以參考下2023-04-04Maven高級(jí)的聚合和繼承的實(shí)現(xiàn)
在軟件開(kāi)發(fā)中,隨著項(xiàng)目規(guī)模的擴(kuò)大,單個(gè)模塊的開(kāi)發(fā)方式逐漸轉(zhuǎn)變?yōu)槎嗄K開(kāi)發(fā),這種方式帶來(lái)了項(xiàng)目管理上的挑戰(zhàn),其中最常見(jiàn)的問(wèn)題是模塊間的依賴(lài)管理和版本控制問(wèn)題,本文就來(lái)介紹一下2024-10-10Spring運(yùn)行時(shí)動(dòng)態(tài)注冊(cè)bean的方法
這篇文章主要介紹了Spring運(yùn)行時(shí)動(dòng)態(tài)注冊(cè)bean的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08java通過(guò)HttpServletRequest獲取post請(qǐng)求中的body內(nèi)容的方法
本篇文章主要介紹了java通過(guò)HttpServletRequest獲取post請(qǐng)求中的body內(nèi)容的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02