20160421javaweb之上传下载小案例---网盘

一、建立数据库:

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

 运行截图:

下载地址:

使劲点我呀

posted @ 2016-04-21 18:59 破玉 阅读(...) 评论(...) 编辑 收藏