接著上一篇講:
Jsp+Servlet實現文件上傳下載(一)--文件上傳
本章來實現一下上傳文件列表展示,同時優化了一下第一章中的代碼。
廢話少說,上代碼
mysql創建附件表
DROP TABLE tbl_accessory;
CREATE TABLE tbl_accessory
(
id INT AUTO_INCREMENT PRIMARY KEY,
file_name VARCHAR(500),
file_size DOUBLE(10,2),
file_ext_name VARCHAR(100),
file_path VARCHAR(2000)
)
;
SELECT * FROM tbl_accessory;
DELETE FROM tbl_accessory;
創建附件實體類
package entity.upload;
/**
* 附件實體類
*
* @author xusucheng
* @create 2017-12-29
**/
public class EntityAccessory {
private int id;
private String fileName;
private double fileSize;
private String file_ext_name;
private String filePath;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public double getFileSize() {
return fileSize;
}
public void setFileSize(double fileSize) {
this.fileSize = fileSize;
}
public String getFile_ext_name() {
return file_ext_name;
}
public void setFile_ext_name(String file_ext_name) {
this.file_ext_name = file_ext_name;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
創建DBUtil工具類
package util;
import java.sql.*;
import java.io.InputStream;
import java.util.Properties;
/**
* 數據庫工具類
*
* @author xusucheng
* @create 2017-11-18
**/
public class DBUtil {
//定義鏈接所需要的變量
private static Connection con = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
//定義鏈接數據庫所需要的參數
private static String url = "";
private static String username = "";
private static String driver="";
private static String password="";
//定義讀取配置文件所需要的變量
private static Properties pp = null;
private static InputStream fis = null;
/**
* 加載驅動
*/
static {
try {
//從dbinfo.properties配置文件中讀取配置信息
pp = new Properties();
fis = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
pp.load(fis);
url = pp.getProperty("url");
username = pp.getProperty("username");
driver=pp.getProperty("driver");
password=pp.getProperty("password");
//加載驅動
Class.forName(driver);
} catch (Exception e) {
System.out.println("驅動加載失敗!");
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
fis = null; //垃圾回收自動處理
}
}
/**
* 得到Connection鏈接
* @return Connection
*/
public static Connection getConnection() {
try {
//建立連接
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println("數據庫鏈接失敗!");
e.printStackTrace();
}
return con;
}
/*public DBUtil(String sql){
try {
ps = getConnection().prepareStatement(sql);//準備執行語句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
/**
* 統一的資源關閉函數
* @param rs
* @param ps
* @param con
*/
public static void close(ResultSet rs,Statement ps, Connection con){
if(rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
創建附件實體DAO類
package dao.upload;
import entity.upload.EntityAccessory;
import util.DBUtil;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 附件上傳DAO
*
* @author xusucheng
* @create 2017-12-29
**/
public class AccessoryDao {
public static void add(EntityAccessory entity) {
Connection conn = DBUtil.getConnection();
String sql = "insert into tbl_accessory(file_name,file_size,file_ext_name,file_path) values(?,?,?,?)";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, entity.getFileName());
ps.setDouble(2, entity.getFileSize());
ps.setString(3, entity.getFile_ext_name());
ps.setString(4, entity.getFilePath());
ps.execute();
//conn.commit();
DBUtil.close(null, ps, conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ListEntityAccessory> list() {
Connection conn = DBUtil.getConnection();
String sql = "select id,file_name,file_size,file_ext_name,file_path from tbl_accessory";
ListEntityAccessory> accessoryList = new ArrayList>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
EntityAccessory entity = new EntityAccessory();
entity.setId(rs.getInt("id"));
entity.setFileName(rs.getString("file_name"));
entity.setFileSize(new BigDecimal(rs.getDouble("file_size") / 1024).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
entity.setFile_ext_name(rs.getString("file_ext_name"));
entity.setFilePath(rs.getString("file_path"));
accessoryList.add(entity);
}
DBUtil.close(rs, ps, conn);
} catch (SQLException e) {
e.printStackTrace();
}
return accessoryList;
}
public static void remove(int id) {
Connection conn = DBUtil.getConnection();
String sql = "delete from tbl_accessory where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,id);
ps.execute();
//conn.commit(); mysql默認開啟了autocommit
DBUtil.close(null,ps,conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
創建list.jsp列表頁面
html>
head>
title>上傳文件列表/title>
/head>
body>
h3>文件列表/h3>
table class="acclist_tab" border="1" bordercolor="#000000" cellspacing="0" cellpadding="2" style="border-collapse:collapse;">
tr>
th>文件名/th>
th>文件大小(KB)/th>
th>操作/th>
/tr>
c:if test="${not empty accessoryList}">
c:forEach items="${accessoryList}" var="acc">
tr>
td>${acc.fileName}/td>
td>${acc.fileSize}/td>
td>a href="">刪除/a>/td>
/tr>
/c:forEach>
/c:if>
/table>
/body>
/html>
創建展示列表Servlet:listUploadedFilesServlet
package servlet.upload;
import dao.upload.AccessoryDao;
import entity.upload.EntityAccessory;
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.IOException;
import java.util.List;
/**
* 返回已上傳文件列表
*
* @author xusucheng
* @create 2017-12-29
**/
@WebServlet("/listUploadedFiles")
public class listUploadedFilesServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取文件列表
ListEntityAccessory> accessoryList = AccessoryDao.list();
request.setAttribute("accessoryList", accessoryList);
request.getRequestDispatcher("pages/upload/list.jsp").forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
增加error.jsp顯示上傳失敗信息
%@ page contentType="text/html;charset=UTF-8" language="java" %>
%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
html>
head>
title>上傳錯誤頁面/title>
/head>
body>
h3>上傳失敗:/h3>
c:if test="${not empty errorMessage}">
%--input type="text" id="errorMessage" value="${errorMessage}" style="color:red;" disabled="disabled">--%>
h4 style="color: red;">${errorMessage}/h4>
/c:if>
/body>
/html>
優化了第一章中的上傳控制器
package servlet.upload;
import dao.upload.AccessoryDao;
import entity.upload.EntityAccessory;
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 {
//設置文件上傳基本路徑
String savePath = this.getServletContext().getRealPath("/WEB-INF/uploadFiles");
//設置臨時文件路徑
String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempFiles");
File tempFile = new File(tempPath);
if (!tempFile.exists()) {
tempFile.mkdir();
}
//定義異常消息
String errorMessage = "";
//創建file items工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//設置緩沖區大小
factory.setSizeThreshold(1024 * 100);
//設置臨時文件路徑
factory.setRepository(tempFile);
//創建文件上傳處理器
ServletFileUpload upload = new ServletFileUpload(factory);
//監聽文件上傳進度
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");
//判斷提交上來的數據是否是上傳表單的數據
if (!ServletFileUpload.isMultipartContent(request)) {
//按照傳統方式獲取數據
return;
}
//設置上傳單個文件的大小的最大值,目前是設置為1024*1024字節,也就是1MB
//upload.setFileSizeMax(1024 * 1024);
//設置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和,目前設置為10MB
upload.setSizeMax(1024 * 1024 * 10);
try {
//使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個ListFileItem>集合,每一個FileItem對應一個Form表單的輸入項
ListFileItem> items = upload.parseRequest(request);
IteratorFileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
//判斷jsp提交過來的是不是文件
if (item.isFormField()) {
errorMessage = "請提交文件!";
break;
} else {
//文件名
String fileName = item.getName();
if (fileName == null || fileName.trim() == "") {
System.out.println("文件名為空!");
}
//處理不同瀏覽器提交的文件名帶路徑問題
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
//文件大小
Long fileSize = item.getSize();
//文件擴展名
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
//判斷擴展名是否合法
if (!validExtension(fileExtension)) {
errorMessage = "上傳文件非法!";
item.delete();
break;
}
//獲得文件輸入流
InputStream in = item.getInputStream();
//得到保存文件的名稱
String saveFileName = createFileName(fileName);
//得到文件保存路徑
String realFilePath = createRealFilePath(savePath, saveFileName);
//創建文件輸出流
FileOutputStream out = new FileOutputStream(realFilePath);
//創建緩沖區
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
//寫文件
out.write(buffer, 0, len);
}
//關閉輸入流
in.close();
//關閉輸出流
out.close();
//刪除臨時文件
item.delete();
span style="color:#FF0000;">//將上傳文件信息保存到附件表中
EntityAccessory entity = new EntityAccessory();
entity.setFileName(fileName);
entity.setFileSize(fileSize);
entity.setFile_ext_name(fileExtension);
entity.setFilePath(realFilePath);
AccessoryDao.add(entity);/span>
}
}
} catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
errorMessage = "單個文件超出最大值!!!";
} catch (FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
errorMessage = "上傳文件的總的大小超出限制的最大值!!!";
} catch (FileUploadException e) {
e.printStackTrace();
errorMessage = "文件上傳失敗!!!";
} finally {
span style="color:#FF0000;">if (!"".equals(errorMessage)) {
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher("pages/upload/error.jsp").forward(request, response);
} else {
response.sendRedirect("listUploadedFiles");
}/span>
}
}
@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;
}
/**
* 根據基本路徑和文件名稱生成真實文件路徑,基本路徑\\年\\月\\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;
}
}
測試效果截圖


下集預告:實現附件刪除功能!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- javascript使用Blob對象實現的下載文件操作示例
- 原生js實現文件上傳、下載、封裝等實例方法
- JavaScript實現文件下載并重命名代碼實例
- php+js實現的無刷新下載文件功能示例
- js使用文件流下載csv文件的實現方法
- 通過JavaScript下載文件到本地的方法(單文件)
- Jsp+Servlet實現文件上傳下載 刪除上傳文件(三)
- Jsp+Servlet實現文件上傳下載 文件上傳(一)
- JSP servlet實現文件上傳下載和刪除
- JavaScript實現多文件下載方法解析