码迷,mamicode.com
首页 > 其他好文 > 详细

黑马day15 仿网盘案例

时间:2015-07-10 09:33:35      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:文件下载和文件上传

项目介绍:

  本项目主要完成文件的上传以及下载的功能的一个综合案例.

1.搭建环境...

   导入jar包以及开发的工具类...

   jar包:

技术分享

提供俩个工具类..一个是IOUtils主要提供了输出流和输入流的对接,和关闭流资源的函数

      一个是提供数据源的工具类DataSourceUtils

IOUtils:

package cn.itheima.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtils {
	private IOUtils(){
		
	}
	/**
	 * 读取流中的数据写到输出流中
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	public static void In2Out(InputStream in,OutputStream out) throws IOException{
		int len=0;
		byte b[]=new byte[1024];
		while((len=in.read(b))!=-1){
			out.write(b, 0, len);
		}
	}
	/**
	 * 关闭资源
	 * @param in
	 * @param out
	 */
	public  static void closeIO(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;
			}
		}
	}
}
DataSourceUtils:

package cn.itheima.utils;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtil {
	private static DataSource source = new ComboPooledDataSource();
	private DataSourceUtil() {
	}
	public static DataSource getSource(){
		return source;
	}
	public static Connection getConn(){
		try {
			return source.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
2.准备好数据库:

create database day15;
use day15;
create table netdisk(
id int primary key auto_increment,
uuidname varchar(255),
realname varchar(255),
savepath varchar(255),
ip varchar(100),
uploadtime timestamp,
description varchar(255)
);

配置文件c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/day15?generateSimpleParameterMetadata=true</property>
    <property name="user">root</property>
    <property name="password">169500</property>
  </default-config>
</c3p0-config>


3.准备javaBean类Resource(要保证和数据库中的属性一致)

package cn.itheima.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 ip;//上传文件者的ip地址
	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 getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}
4.搭建项目的主页面:主要提供两个超链接:文件上传的超链接-->upload.jsp,文件下载列表的超链接-->

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
	<meta http-equiv=" pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
    <a href="${pageContext.request.contextPath }/upload.jsp">文件上传</a>
      <a href="${pageContext.request.contextPath }/servlet/DownLoadListServlet">文件列表</a>
  </body>
</html>

技术分享

5.开发load.jsp上传文件的页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
	<meta http-equiv=" pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
  <h1>文件上传</h1>
    <form action="${pageContext.request.contextPath }/servlet/UploadServlet" enctype="multipart/form-data" method="post">
    	描述信息:<input type="text" name="description"/><br>
    	文件上传:<input type="file" name="file1"/><br>
    	<input type="submit" value="提交"/><br>
    </form>
  </body>
</html>
技术分享



6.开发servlet类UploadServlet(需要在WEB-INF目录下建立temp临时文件夹以及upload的上传文件所在的文件夹)

(1).上传文件的步骤

(2).将拿到的数据封装到Resource的一个对象中...这里使用的是BeanUtils..

(3).添加数据到数据库中...

(4).重定向到主页..

注意:

  这里保存到数据库的路径不是全路径而是截取硬盘路径后的路径...

  封装数据拿不到所有的数据,因此自己建立一个map类封装数据...

  这里采用的是hashcode的文件夹存储...

package cn.itheima.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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.org.apache.commons.beanutils.BeanUtils;

import cn.itheima.domain.Resource;
import cn.itheima.utils.DataSourceUtil;
import cn.itheima.utils.IOUtils;

public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map map=new HashMap();
		String ip= request.getRemoteAddr();
		map.put("ip", ip);
		try {
			// 1.文件上传的工厂类
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(this.getServletContext()
					.getRealPath("WEB-INF/temp")));
			// 2.文件上传用到的核心类
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			fileUpload.setFileSizeMax(1024 * 1024 * 100);// 设置单个文件的大小
			fileUpload.setFileSizeMax(1024 * 1024 * 300);// 设置总的文件的大小
			fileUpload.setHeaderEncoding("utf-8");// 解决中文乱码的问题
			// 3.判断表单的类型
			if (!fileUpload.isMultipartContent(request)) {
				throw new RuntimeException("请使用正确的表单类型");
			}
			// --解析request
			List<FileItem> list = fileUpload.parseRequest(request);
			//--遍历
			for(FileItem item:list){
				if(item.isFormField()){//普通字段
					String name = item.getFieldName();
					String value = item.getString("utf-8");
					map.put(name, value);
				}else{//文件上传字段
					String realname = item.getName();
					map.put("realname", realname);
					String uuidname=UUID.randomUUID()+"_"+realname;
					map.put("uuidname", uuidname);
					String str = Integer.toHexString(uuidname.hashCode());
					String path=this.getServletContext().getRealPath("WEB-INF/upload");
					String savepath = "/WEB-INF/upload";
					for(char c:str.toCharArray()){
						path+="/"+c;
						savepath+="/"+c;
					}
					map.put("savepath",savepath);
					//--创建文件夹
					new File(path).mkdirs();
					InputStream in=item.getInputStream();
					OutputStream out=new FileOutputStream(new File(path,uuidname));
					IOUtils.In2Out(in, out);
					IOUtils.closeIO(in, out);
					item.delete();//删除临时文件
				}
			}
			//2.存到数据库中
			//--封装数据
			Resource r=new Resource();
			BeanUtils.populate(r,map);
			QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
			String sql="insert into netdisk values(null,?,?,?,?,null,?)";
			runner.update(sql,r.getUuidname(),r.getRealname(),r.getId(),r.getSavepath(),r.getDescription());
			//3.重定向回主页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
7.回归到主页...开发DownLoadListServlet

(1).数据库查询数据封装到list集合中

(2).把list放到request域中...用于在列表显示..

(3).请求转发到list.jsp

package cn.itheima.web;

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 javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.itheima.domain.Resource;
import cn.itheima.utils.DataSourceUtil;

public class DownLoadListServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.查询数据库
		QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
		String sql="select * from netdisk  ";
		List list=null;
		try {
			list=runner.query(sql, new BeanListHandler<Resource>(Resource.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("list", list);
		request.getRequestDispatcher("/list.jsp").forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
8.开发list.jsp遍历list中的数据...

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
	<meta http-equiv=" pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
    <h1>下载列表</h1>
    <c:forEach items="${requestScope.list }" var="li">
    	文件名:${li.realname }<br>
    	上传者ip:${li.ip }<br>
    	上传时间:${li.uploadtime}<br>
    	文件描述:${li.description }<br>
    	<a href="${pageContext.request.contextPath }/servlet/DownLoadServlet?id=${li.id}">下载</a><br>
    </c:forEach>
  </body>
</html>
技术分享



9.开发DownLoadServlet(要注意的是下载的路径要拼接..因为存放到数据库中的路径是WEB-INF/upload....)

(1).获取id

(2).通过id查询数据库...拿到javaBean

(3).按照下载的步骤写代码...

(4).重定向到下载列表页面

package cn.itheima.web;

import java.io.FileInputStream;
import java.io.FileOutputStream;
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 javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.itheima.domain.Resource;
import cn.itheima.utils.DataSourceUtil;
import cn.itheima.utils.IOUtils;

public class DownLoadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.获取下载文件的id
		String id = request.getParameter("id");
		Resource r=null;
		String sql="select * from netdisk where id=?";
		QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
		try {
			r=runner.query(sql, new BeanHandler<Resource>(Resource.class),id);
			response.setHeader("Content-Disposition", "attchment;filename="+URLEncoder.encode(r.getRealname(),"utf-8"));
			response.setContentType(this.getServletContext().getMimeType(r.getRealname()));
			String path=r.getSavepath();
			String savepath=this.getServletContext().getRealPath(path+"/"+r.getUuidname());
			InputStream in=new FileInputStream(savepath);
			OutputStream out=response.getOutputStream();
			IOUtils.In2Out(in, out);
			IOUtils.closeIO(in, out);
			response.sendRedirect(request.getContextPath()+"/list.jsp");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

黑马day15 仿网盘案例

标签:文件下载和文件上传

原文地址:http://blog.csdn.net/u014010769/article/details/46822179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!