一、建立数据库:

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&amp;characterEncoding=utf-8</property>
<property name="user">root</property>
<property name="password"></property>
</default-config>
</c3p0-config>

c3p0-config.xml

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;
} }

Resource.java

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);
}
}
}

DaoUtils.java

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;
}
}
}
}

IOUtils.java

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);
} }

UploadServlet.java

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);
} }

DownListServlet.java

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);
} }

DownServlet.java

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>

index.jsp

<%@ 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>

upload.jsp

<%@ 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>

downlist.jsp

运行截图:

下载地址:

使劲点我呀

20160421javaweb之上传下载小案例---网盘的更多相关文章

  1. 【Android 应用开发】Android 开发环境下载地址 -- 百度网盘 adt-bundle android-studio sdk adt 下载

    19af543b068bdb7f27787c2bc69aba7f Additional Download (32-, 64-bit) Package r10 STL debug info androi ...

  2. yarn-1.12.3.msi 下载地址 百度网盘

    yarn-1.12.3.msi 下载地址 百度网盘 链接:https://pan.baidu.com/s/1-JEO1as0Jtp1a1pAqW-mzg 提取码:lbz0

  3. 文件分享工具ShareLocalFile不需要云盘的实时上传下载文件的云盘工具可以搜索整个网络的文件

    工具的下载地址:https://comm.zhaimaojun.cn/AllSources/ToolDetail/?tid=9693 这是一个未来的项目,可以分享我们的文件,目前由于个人的技术水平限制 ...

  4. Linux命令行上传文件到百度网盘

    利用bpcs_uploader你可以自动将VPS主机上的文件上传到百度网盘中,同时也可以从百度网盘中下载文件到VPS主机上,让你的文件安全地"住"在百度云中.[font=Tahom ...

  5. Android 开发环境下载地址 -- 百度网盘 adt-bundle android-studio sdk adt 下载

    最近 Google 被墙了, 上传一下自己收集的 Android 开发环境, 下面给出的官网链接也可以下载; http://www.androiddevtools.cn/ 1. 百度网盘下载地址 An ...

  6. VPS搭建离线下载服务器——后网盘时代

    动机 由于学习的需要,在国外某服务器厂商购买了vps服务(至于是哪个厂商就不说啦).但是呢,就算用作梯子,一个月1T的流量总是用不完.最经觉得自己营养充足,想找点电影看看. 无奈现在百度网盘的速度真的 ...

  7. 微信小程序——网盘图片预览

    微信小程序图片预览提供了一个wx.previewImage接口,如下图: 现在我需要对网盘文件里的图片预览,但是网盘从后台返回的数据是各种类型的文件,如下图所示: 那么我们需要解决2个问题: 1.从这 ...

  8. centeros系统之上传下载文件

    安装lrzszlrzsz这个软件,可以让我们直接从linux上,下载和上传文件的操作 yum install -y lrzsz11.上传文件通过输入 rz命令,可以弹出上传文件的对话框,然后就可以上传 ...

  9. 微信小程序之上传下载交互api

    wx.request(OBJECT) OBJECT参数说明: 参数名 类型 必填 说明 url String 是 开发者服务器接口地址 data Object.String 否 请求的参数 heade ...

随机推荐

  1. C# #if DEBUG

    首先,大小写不能写错,其次,解决方案配置设为:Debug,才会执行该语句,如果在条件里面搭配Debug.Assert等,效果甚佳.而如果要设置为Release模式,就不会执行条件语句中的内容,有时候可 ...

  2. 使用Spring MVC 的表单控制器SimpleFormController

    以注册过程为例,我们可能会选择继承AbstractController来实现表单的显示,继承AbstractCommandController来实现表单的处理 ,这样是可行的,但必须要维护两个控制器 ...

  3. [liu yanling]测试用例作用

    ⒈指导测试的实施 测试用例主要适用于集成测试.系统测试和回归测试.在实施测试时测试用例作为测试的标准,测试人员一定要按照测试用例严格按用例项目和测试步骤逐一实施测试.并对测试情况记录在测试用例管理软件 ...

  4. 察看so文件的依赖关系

    使用arm-linux-androideabi-readelf 察看依赖动态库 /android-ndk-r8d/toolchains/arm-linux-androideabi-4.7/prebui ...

  5. editpuls查找替换通配符

    1  \t    Tab character.         tab符号 2  \n    New line.              新的一行(换行符) 3  .     Matches any ...

  6. grep环境变量常用配置

    vim ~/.bashrc GREP_OPTIONS="-irns --exclude-dir=output --exclude=tags --exclude=*.files" 然 ...

  7. NDK编译路径问题

    有点偷懒,在一个使用了jni工程里面稍微修改一下,编译另外一个jni工程. 代码写完后,Android.mk等文件也写好,但是ndk-build的时候提示Android NDK:Your APP_BU ...

  8. hdoj 2955 Robberies

    Robberies Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  9. jQuery语法基础&选择器

    jQuery 语法 jQuery 语法是为 HTML 元素的选取编制的,可以对元素执行某些操作. 基础语法是:$(selector).action() 美元符号定义 jQuery 选择符(select ...

  10. Oracle数据库编程:PL/SQL编程基础

    2.PL/SQL编程基础: PL/SQL块:        declare        定义部分        begin        执行部分        exception        异 ...