一、建立資料庫:
CREATE TABLE IF NOT EXISTS `netdisk` ( `id` int(10) NOT NULL AUTO_INCREMENT, `uuidname` varchar(255) NOT NULL, `realname` varchar(255) NOT NULL, `savepath` varchar(255) NOT NULL, `uploadtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `description` varchar(255) NOT NULL, `ip` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
二、功能分析:
index.jsp --- 提供 上傳 下載列表
upload.jsp --- 提供上傳表單,允許使用者選擇檔案進行上傳
UploadServlet --- 儲存上傳的檔案到伺服器/在資料庫中儲存檔案相關的資訊
DownListServlet --- 查詢資料庫表找到所有可供下載的資源資訊,存入request域後帶到頁面顯示
downlist.jsp --- 遍歷request中所有資源資訊,提供下載連線
DownServlet --- 下載指定id的資源
三、程式碼:
工程結構:
1.c3p0的配置檔案,位於src目錄
<c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/0417?Unicode=true&characterEncoding=utf-8</property> <property name="user">root</property> <property name="password"></property> </default-config> </c3p0-config>
2.javabean 類位於domain包
package com.dzq.domain; import java.io.Serializable; import java.sql.Timestamp; public class Resource implements Serializable { private int id; private String uuidname; // 上傳檔案的名稱,檔案的uuid名 private String realname; // 上傳檔案的真實名稱 private String savepath; // 記住檔案的位置 private Timestamp uploadtime; // 檔案的上傳時間 private String description; // 檔案的描述 private String ip; 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; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
3.工具類位於utils包
package com.dzq.utils; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DaoUtils { private static DataSource source = new ComboPooledDataSource(); private DaoUtils() { } public static DataSource getSource() { return source; } public static Connection getConnection() { try { return source.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
package com.dzq.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IOUtils { private IOUtils(){ } public static void In2Out(InputStream in,OutputStream out) throws IOException{ byte[] bs=new byte[1024]; int i=0; while ((i=in.read(bs))!=-1) { out.write(bs,0,i); } } public static void close(InputStream in,OutputStream out){ if(in!=null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); }finally{ in=null; } } if(out!=null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); }finally{ out=null; } } } }
4.servlet位於web包
package com.dzq.web; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; 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 org.apache.commons.beanutils.BeanUtils; 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 com.dzq.domain.Resource; import com.dzq.utils.DaoUtils; import com.dzq.utils.IOUtils; @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1.上傳檔案 // 設定檔案上傳的路徑和臨時路徑 String upload = this.getServletContext().getRealPath( "/WEB-INF/upload"); String temp = this.getServletContext().getRealPath("/WEB-INF/temp"); Map pmap = new HashMap(); pmap.put("ip", request.getRemoteAddr()); // 建立工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設定記憶體 factory.setSizeThreshold(1024 * 100); // 設定臨時目錄 factory.setRepository(new File(temp)); ServletFileUpload fileupload = new ServletFileUpload(factory); // 防止檔案中文名亂碼 fileupload.setHeaderEncoding("utf-8"); // 設定單個檔案最大值 fileupload.setFileSizeMax(1024 * 1024 * 100); // 設定總檔案最大值 fileupload.setSizeMax(1024 * 1024 * 200); // 檢查表單是否正確 if (!fileupload.isMultipartContent(request)) { throw new RuntimeException("表單不正確"); } List<FileItem> list = fileupload.parseRequest(request); for (FileItem item : list) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString("utf-8"); pmap.put(name, value); } else { // 獲取檔名 String realname = item.getName(); // 設定檔案的UUID檔名,防止檔名重複 String uuidname = UUID.randomUUID().toString() + "_" + realname; // 計算uuid雜湊值 String hash = Integer.toHexString(uuidname.hashCode()); String savepath = "/WEB-INF/upload"; pmap.put("realname", realname); pmap.put("uuidname", uuidname); InputStream in = item.getInputStream(); for (char c : hash.toCharArray()) { // 根據雜湊值分佈儲存 upload += "/" + c; savepath += "/" + c; } new File(upload).mkdirs(); pmap.put("savepath", savepath); OutputStream out = new FileOutputStream(new File(upload, uuidname)); IOUtils.In2Out(in, out); IOUtils.close(in, out); // 刪除臨時檔案 item.delete(); } } // 2.向資料庫寫入資料 Resource r = new Resource(); BeanUtils.populate(r, pmap); QueryRunner runner = new QueryRunner(DaoUtils.getSource()); String sql = "insert into netdisk values (null,?,?,?,null,?,?)"; runner.update(sql, r.getUuidname(), r.getRealname(), r.getSavepath(), r.getDescription(), r.getIp()); // 3.重定向回主頁 response.sendRedirect(request.getContextPath() + "/index.jsp"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.dzq.web; import java.io.IOException; import java.sql.SQLException; import java.util.List; 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 org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.dzq.domain.Resource; import com.dzq.utils.DaoUtils; @WebServlet("/DownListServlet") public class DownListServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.查詢資料庫中所有可供下載的資源 String sql = "select * from netdisk "; QueryRunner runner = new QueryRunner(DaoUtils.getSource()); List<Resource> list = null; try { list = runner.query(sql, new BeanListHandler<Resource>( Resource.class)); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } // 2.存入request域 request.setAttribute("list", list); request.getRequestDispatcher("/downlist.jsp") .forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.dzq.web; 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.annotation.WebServlet; 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 com.dzq.domain.Resource; import com.dzq.utils.DaoUtils; import com.dzq.utils.IOUtils; @WebServlet("/DownServlet") public class DownServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); String sql = "select * from netdisk where id=?"; QueryRunner runner = new QueryRunner(DaoUtils.getSource()); Resource r = null; try { r = runner .query(sql, new BeanHandler<Resource>(Resource.class), id); } catch (SQLException e) { e.printStackTrace(); } if (r == null) { response.getWriter().write("對不起,資源不存在了"); return; } else { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(r.getRealname(), "utf-8")); response.setContentType(this.getServletContext().getMimeType( r.getRealname()));// MIME型別 String filepath = this.getServletContext().getRealPath( r.getSavepath() + "/" + r.getUuidname()); InputStream in = new FileInputStream(new File(filepath)); OutputStream out = response.getOutputStream(); IOUtils.In2Out(in, out); IOUtils.close(in, out); IOUtils.close(in, null); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
5.jsp頁面,位於WebContent目錄下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>小強網盤</h1><hr> <a href="${pageContext.request.contextPath }/upload.jsp">上傳</a> <a href="${pageContext.request.contextPath }/DownListServlet">下載列表</a> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>上傳頁面</h1><hr> <form action="${pageContext.request.contextPath }/UploadServlet" method="post" enctype="multipart/form-data"> 選擇檔案:<input type="file" name="file1"/><br> 描述資訊:<textarea rows="5" cols="45" name="description"></textarea><br> <input type="submit" value="上傳"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>下載列表</h1><hr> <c:forEach items="${requestScope.list }" var="r"> <h2>檔名:${r.realname }</h2><br> 上傳時間:${r.uploadtime }<br> 上傳者IP:${r.ip }<br> 描述資訊:${r.description }<br> <a href="${pageContext.request.contextPath }/DownServlet?id=${r.id}">下載</a> <hr> </c:forEach> </body> </html>
執行截圖:
下載地址:
使勁點我呀