接着上一篇讲:
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 list<entityaccessory> list() {
connection conn = dbutil.getconnection();
string sql = "select id,file_name,file_size,file_ext_name,file_path from tbl_accessory";
list<entityaccessory> 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 {
//获取文件列表
list<entityaccessory> 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解析器解析上传数据,解析结果返回的是一个list<fileitem>集合,每一个fileitem对应一个form表单的输入项
list<fileitem> items = upload.parserequest(request);
iterator<fileitem> 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;
}
}
测试效果截图
下集预告:实现附件删除功能!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
申明:本教程内容由威凡网编辑整理并提供IT程序员分享学习,如文中有侵权行为,请与站长联系(QQ:254677821)!