接著上一篇講:
Jsp+Servlet實(shí)現(xiàn)文件上傳下載(一)--文件上傳
本章來實(shí)現(xiàn)一下上傳文件列表展示,同時(shí)優(yōu)化了一下第一章中的代碼。
廢話少說,上代碼
mysql創(chuàng)建附件表
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;
創(chuàng)建附件實(shí)體類
package entity.upload;
/**
* 附件實(shí)體類
*
* @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;
}
}
創(chuàng)建DBUtil工具類
package util;
import java.sql.*;
import java.io.InputStream;
import java.util.Properties;
/**
* 數(shù)據(jù)庫工具類
*
* @author xusucheng
* @create 2017-11-18
**/
public class DBUtil {
//定義鏈接所需要的變量
private static Connection con = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
//定義鏈接數(shù)據(jù)庫所需要的參數(shù)
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;
/**
* 加載驅(qū)動(dòng)
*/
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");
//加載驅(qū)動(dòng)
Class.forName(driver);
} catch (Exception e) {
System.out.println("驅(qū)動(dòng)加載失?。?);
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
fis = null; //垃圾回收自動(dòng)處理
}
}
/**
* 得到Connection鏈接
* @return Connection
*/
public static Connection getConnection() {
try {
//建立連接
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println("數(shù)據(jù)庫鏈接失??!");
e.printStackTrace();
}
return con;
}
/*public DBUtil(String sql){
try {
ps = getConnection().prepareStatement(sql);//準(zhǔn)備執(zhí)行語句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
/**
* 統(tǒng)一的資源關(guān)閉函數(shù)
* @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();
}
}
}
}
創(chuàng)建附件實(shí)體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默認(rèn)開啟了autocommit
DBUtil.close(null,ps,conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
創(chuàng)建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>文件大?。↘B)/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>
創(chuàng)建展示列表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>上傳錯(cuò)誤頁面/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>
優(yōu)化了第一章中的上傳控制器
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 {
//設(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)聽文件上傳進(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");
//判斷提交上來的數(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è)ListFileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng)
ListFileItem> items = upload.parseRequest(request);
IteratorFileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
//判斷jsp提交過來的是不是文件
if (item.isFormField()) {
errorMessage = "請?zhí)峤晃募?;
break;
} else {
//文件名
String fileName = item.getName();
if (fileName == null || fileName.trim() == "") {
System.out.println("文件名為空!");
}
//處理不同瀏覽器提交的文件名帶路徑問題
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
//文件大小
Long fileSize = item.getSize();
//文件擴(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í)文件
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 = "單個(gè)文件超出最大值?。?!";
} 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;
}
/**
* 根據(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;
}
}
測試效果截圖
下集預(yù)告:實(shí)現(xiàn)附件刪除功能!
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- javascript使用Blob對(duì)象實(shí)現(xiàn)的下載文件操作示例
- 原生js實(shí)現(xiàn)文件上傳、下載、封裝等實(shí)例方法
- JavaScript實(shí)現(xiàn)文件下載并重命名代碼實(shí)例
- php+js實(shí)現(xiàn)的無刷新下載文件功能示例
- js使用文件流下載csv文件的實(shí)現(xiàn)方法
- 通過JavaScript下載文件到本地的方法(單文件)
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 刪除上傳文件(三)
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
- JSP servlet實(shí)現(xiàn)文件上傳下載和刪除
- JavaScript實(shí)現(xiàn)多文件下載方法解析