文件上传下载案例
bean:
package bean;
import java.sql.Timestamp;
public class Resources {
private int id;
private String uuidname;
private String realname;
private String savepath;
private Timestamp uploadtime;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUuidname() {
return uuidname;
}
public void setUuidname(String uuidname) {
this.uuidname = uuidname;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getSavepath() {
return savepath;
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public Timestamp getUploadtime() {
return uploadtime;
}
public void setUploadtime(Timestamp uploadtime) {
this.uploadtime = uploadtime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DownServlet:(完成下载)
package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.io.IOUtils;
import com.mchange.util.Base64Encoder;
import bean.Resources;
import sun.misc.BASE64Encoder;
import utils.C3P0Utils;
//当前servlet用于完成文件下载功能
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//取出文件名
String filename = request.getParameter("filename");
//处理get方式中文乱码问题
filename = new String(filename.getBytes("ISO-8859-1"),"utf-8");
//根据文件名查询数据库
QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from resources where uuidname=?";
try {
Resources resource = runner.query(sql, new BeanHandler<Resources>(Resources.class),filename);
//把查询到的文件读取进来
//因为保存到的时候是uuidname,所以取的时候要用uuidname来取
InputStream in = new FileInputStream(new File(resource.getSavepath(), resource.getUuidname()));
OutputStream out = response.getOutputStream();
//解决下载文件名的中文乱码
String userAgent = request.getHeader("User-Agent");
if(userAgent.contains("MSIE")){
//IE浏览器
filename = URLEncoder.encode(filename,"utf-8");
filename = filename.replace("+", "");
}else{
//其他浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
}
//通知浏览器一下载的形式查看文件
response.setContentType(getServletContext().getMimeType(resource.getRealname()));
response.setHeader("Content-Disposition", "attachement;filename="+resource.getRealname());
IOUtils.copy(in, out);
in.close();
out.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ListServlet:(下载列表)
package servlet;
import java.io.IOException;
import java.sql.SQLException;
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.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import bean.Resources;
import utils.C3P0Utils;
//当前servlet用于完成下载文件列表功能
public class ListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from resources";
try {
List<Resources> resources = runner.query(sql, new BeanListHandler<Resources>(Resources.class));
request.getSession().setAttribute("resources", resources);
response.sendRedirect("/NetDisk/list.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
UploadServlet:(上传功能)
package servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
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;
import org.apache.commons.io.IOUtils;
import utils.C3P0Utils;
import bean.Resources;
//此servlet用于完成上传功能
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String UUIDName = null;
String fileName = null;
String realPath = null;
String fieldValue = null;
long uploadtime = 0;
//解决中文乱码
request.setCharacterEncoding("utf-8");
//实现文件上传
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定上传的缓存大小
factory.setSizeThreshold(1024*1024*3);
//设置上传的临时目录
factory.setRepository(new File("/WEB-INF/tmp"));
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items;
try {
items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if(fileItem.isFormField()){
//普通项
String fieldName = fileItem.getFieldName();
fieldValue = fileItem.getString("utf-8");
}else{
//上传项
fileName = fileItem.getName();
//解决浏览器过旧的问题,对上传的文件名进行处理:
int index = fileName.lastIndexOf("\\");
if(index>=0){
fileName.substring(index+1);
}
//为了防止文件同名,给文件增加一个唯一的id
UUIDName = UUID.randomUUID().toString()+"_"+fileName;
//得到输入流
InputStream in = new BufferedInputStream(fileItem.getInputStream());
//得到输出流 (输出到的地方 WEB-INF下的files:保存文件的地方)
realPath = getServletContext().getRealPath("/WEB-INF/files");
// realPath = getServletContext().getRealPath("F:\\apache-tomcat-8.5.0\\webapps\\NetDisk\\WEB-INF");
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(realPath,UUIDName)));
IOUtils.copy(in, out);
//删除临时文件
fileItem.delete();
uploadtime = System.currentTimeMillis();
//关流
in.close();
out.close();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
///将相关上传文件的信息封装到javabean中
Resources resources = new Resources();
resources.setUuidname(UUIDName);
resources.setRealname(fileName);
resources.setSavepath(realPath);
resources.setUploadtime(new Timestamp(uploadtime));
resources.setDescription(fieldValue);
//将封装在javabean中的数据插入到对应的数据库表中
QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "insert into resources values(null,?,?,?,?,?)";
try {
runner.update(sql,
resources.getUuidname(),resources.getRealname(),resources.getSavepath(),
resources.getUploadtime(),resources.getDescription());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//通知用户文件上传成功
request.setAttribute("msg", "恭喜你,文件上传成功了");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
utils:
C3P0Utils:
package utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//获取数据源
public static DataSource getDataSource() {
return dataSource;
}
//获得连接
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
//释放资源
public static void close(Statement stmt, Connection conn){
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void close(Statement stmt, Connection conn, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
c3p0-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day0109</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
index.jsp:
<body>
<h1>我的网盘</h1>
<a href="upload.jsp">文件上传</a>
<a href="${pageContext.request.contextPath }/servlet/ListServlet">文件下载列表</a>
</body>
list.jsp:
<!-- 从session中把存放进去的下载列表取出来 -->
</head>
<h1>文件下载列表</h1>
<c:forEach var="resource" items="${resources }">
<hr>
<h3>文件名称:${resource.realname }</h3>
<h3><a href="servlet/DownServlet?filename=${resource.uuidname }">下载</a></h3>
<h3>文件描述:</h3>
<p>${resource.description }</p>
</c:forEach>
<body>
</body>
message.jsp:
<!-- 刷新跳转到主页面 -->
<meta http-equiv="Refresh" content="5,url=index.jsp">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>${msg }</h1>
</body>
upload.jsp:
<body>
<h1>文件上传</h1>
<form action="${pageContext.request.contextPath }/servlet/UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="upload"><br>
文件描述:<input type="text" name="description"><br>
<input type="submit" value="上传">
</form>
</body>
数据库: