Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
文件上傳和下載功能是Java Web必備技能,很實(shí)用。
本文使用的是Apache下的著名的文件上傳組件
org.apache.commons.fileupload 實(shí)現(xiàn)
下面結(jié)合最近看到的一些資料以及自己的嘗試,先寫第一篇文件上傳。后續(xù)會(huì)逐步實(shí)現(xiàn)下載,展示文件列表,上傳信息持久化等。
廢話少說(shuō),直接上代碼
第一步、引用jar包,設(shè)置上傳目錄
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
上傳目錄:WEB-INF/tempFiles和WEB-INF/uploadFiles
第二步、編寫JSP頁(yè)面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>文件上傳測(cè)試</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="<%=request.getContextPath()%>/UploadServlet">
文件: <input type="file" name="upfile"><br/>
<br/>
<input type="submit" value="上傳">
</form>
<c:if test="${not empty errorMessage}">
<input type="text" id="errorMessage" value="${errorMessage}" style="color:red;" disabled="disabled">
</c:if>
</body>
</html>
第三步、編寫Servlet,處理文件上傳的核心
package servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
/**
* 處理文件上傳
*
* @author xusucheng
* @create 2017-12-27
**/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設(shè)置文件上傳基本路徑
String savePath = this.getServletContext().getRealPath("/WEB-INF/uploadFiles");
//設(shè)置臨時(shí)文件路徑
String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempFiles");
File tempFile = new File(tempPath);
if (!tempFile.exists()) {
tempFile.mkdir();
}
//定義異常消息
String errorMessage = "";
//創(chuàng)建file items工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//設(shè)置緩沖區(qū)大小
factory.setSizeThreshold(1024 * 100);
//設(shè)置臨時(shí)文件路徑
factory.setRepository(tempFile);
//創(chuàng)建文件上傳處理器
ServletFileUpload upload = new ServletFileUpload(factory);
//監(jiān)聽(tīng)文件上傳進(jìn)度
ProgressListener progressListener = new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("正在讀取文件: " + pItems);
if (pContentLength == -1) {
System.out.println("已讀?。?" + pBytesRead + " 剩余0");
} else {
System.out.println("文件總大?。? + pContentLength + " 已讀取:" + pBytesRead);
}
}
};
upload.setProgressListener(progressListener);
//解決上傳文件名的中文亂碼
upload.setHeaderEncoding("UTF-8");
//判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)
if (!ServletFileUpload.isMultipartContent(request)) {
//按照傳統(tǒng)方式獲取數(shù)據(jù)
return;
}
//設(shè)置上傳單個(gè)文件的大小的最大值,目前是設(shè)置為1024*1024字節(jié),也就是1MB
upload.setFileSizeMax(1024 * 1024);
//設(shè)置上傳文件總量的最大值,最大值=同時(shí)上傳的多個(gè)文件的大小的最大值的和,目前設(shè)置為10MB
upload.setSizeMax(1024 * 1024 * 10);
try {
//使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng)
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
//判斷jsp提交過(guò)來(lái)的是不是文件
if (item.isFormField()) {
errorMessage = "請(qǐng)?zhí)峤晃募?;
break;
} else {
//文件名
String fileName = item.getName();
if (fileName == null || fileName.trim() == "") {
System.out.println("文件名為空!");
}
//處理不同瀏覽器提交的文件名帶路徑問(wèn)題
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
//文件擴(kuò)展名
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
//判斷擴(kuò)展名是否合法
if (!validExtension(fileExtension)) {
errorMessage = "上傳文件非法!";
item.delete();
break;
}
//獲得文件輸入流
InputStream in = item.getInputStream();
//得到保存文件的名稱
String saveFileName = createFileName(fileName);
//得到文件保存路徑
String realFilePath = createRealFilePath(savePath, saveFileName);
//創(chuàng)建文件輸出流
FileOutputStream out = new FileOutputStream(realFilePath);
//創(chuàng)建緩沖區(qū)
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
//寫文件
out.write(buffer, 0, len);
}
//關(guān)閉輸入流
in.close();
//關(guān)閉輸出流
out.close();
//刪除臨時(shí)文件 TODO
item.delete();
//將上傳文件信息保存到附件表中 TODO
}
}
} catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("errorMessage", "單個(gè)文件超出最大值?。?!");
request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
return;
} catch (FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("errorMessage", "上傳文件的總的大小超出限制的最大值?。?!");
request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
return;
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("errorMessage", "文件上傳失敗?。。?);
request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
return;
}
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private boolean validExtension(String fileExtension) {
String[] exts = {"jpg", "txt", "doc", "pdf"};
for (int i = 0; i < exts.length; i++) {
if (fileExtension.equals(exts[i])) {
return true;
}
}
return false;
}
private String createFileName(String fileName) {
return UUID.randomUUID().toString() + "_" + fileName;
}
/**
* 根據(jù)基本路徑和文件名稱生成真實(shí)文件路徑,基本路徑\\年\\月\\fileName
*
* @param basePath
* @param fileName
* @return
*/
private String createRealFilePath(String basePath, String fileName) {
Calendar today = Calendar.getInstance();
String year = String.valueOf(today.get(Calendar.YEAR));
String month = String.valueOf(today.get(Calendar.MONTH) + 1);
String upPath = basePath + File.separator + year + File.separator + month + File.separator;
File uploadFolder = new File(upPath);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
String realFilePath = upPath + fileName;
return realFilePath;
}
}
第四步、測(cè)試
http://localhost:8080/helloweb/pages/upload/upload.jsp


以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jsp頁(yè)面中兩種方法顯示當(dāng)前時(shí)間的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇jsp頁(yè)面中兩種方法顯示當(dāng)前時(shí)間的簡(jiǎn)單實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06
jsp登錄注冊(cè)完整實(shí)現(xiàn)代碼(增刪改查+網(wǎng)頁(yè)+數(shù)據(jù)庫(kù))
這篇文章主要給大家介紹了關(guān)于jsp登錄注冊(cè)完整實(shí)現(xiàn)代碼的相關(guān)資料,其中包括增刪改查+網(wǎng)頁(yè)+數(shù)據(jù)庫(kù),文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用jsp具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01
springMVC解決ajax請(qǐng)求亂碼的三種方法
這篇文章主要介紹了springMVC解決ajax請(qǐng)求亂碼的三種方法的相關(guān)資料,在springmvc的項(xiàng)目中,使用返回頁(yè)面的請(qǐng)求方式,數(shù)據(jù)都能正常顯示,但是對(duì)于ajax的請(qǐng)求,始終顯示亂碼,這里提供解決辦法,需要的朋友可以參考下2017-07-07
JSP自定義標(biāo)簽Taglib實(shí)現(xiàn)過(guò)程重點(diǎn)總結(jié)
Taglib指令,其實(shí)就是定義一個(gè)標(biāo)簽庫(kù)以及自定義標(biāo)簽的前綴,其中的具體的實(shí)現(xiàn)方式,我們不過(guò)多介紹,我們給大家從宏觀的角度以及解決其中的疑難點(diǎn),感興趣的朋友可以了解下,或許對(duì)你學(xué)習(xí)jsp有所幫助2013-02-02

