使用数据库和javabean实现上传与下载

首先,我是部分参考网址,其中写的最好的莫过于https://blog.csdn.net/a15920804969/article/details/78497668

总体构造图

(1)domain

file.java

package download_upload.domian;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

@Data

@AllArgsConstructor

public class file {

    private Long id;

    private String uuidname;

    private String filename;

    private String savepath;

    private String uploadtime;

    private String description;

    private String username;

    public file(){}

    

    public file(String uuidname, String filename, String savepath, String uploadtime, String description,

            String username) {

        super();

        this.uuidname = uuidname;

        this.filename = filename;

        this.savepath = savepath;

        this.uploadtime = uploadtime;

        this.description = description;

        this.username = username;

    }

    

}

前端页面

index.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>

       <a href="${pageContext.request.contextPath }/upload.jsp">上传文件</a><br/>

<!--     <a href="/file_upload_download/upload.jsp">上传文件</a><br/> -->

       <a href="${pageContext.request.contextPath }/listfile">查询文件</a><br/>

</body>

</html>

upload.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>

 <!--

privateString savepath;     //记住文件的位置

privateDate uploadtime;     //文件的上传时间

privateString description;  //文件的描述

  -->

 <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">

 <table>

 <tr>

 <td>上传文件名</td><td><input type="file"name="filename"></td>

 </tr>

  <tr>

 <td>上传者</td><td><input type="text"name="username"></td>

 </tr>

  <tr>

 <td>上传描述</td><td><textarea name="description"rows="5" cols="30"></textarea></td>

 </tr>

  <tr>

  <tr>

 <td colspan="2"align="center"><input type="submit"value="提交" /> <input type="reset"value="重置"/></td>

 </tr>

 </table>

 </form>

</body>

</html>

message.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>

    ${message}

</body>

</html>

list.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>

    <table align="center"border="1">

<tr>

<th>上传者</th><th>上传文件名</th><th>上传时间</th><th>文件位置</th><th>文件描述</th><th>下载</th>

</tr>

<c:forEach var="file" items="${list }">

<tr>

<td>${file.username }</td>

<td>${file.filename }</td>

<td>${file.uploadtime }</td>

<td>${file.savepath }</td>

<td>${file.description }</td>

<td><font color="red"><a href="${pageContext.request.contextPath}/download?id=${file.id}">下载</a></font></td>

</tr>

</c:forEach>

</table>

</body>

</html>

type接口的编写

type.java

package download_upload.javabean;

import java.sql.ResultSet;

public interface type <T>{

    T hanlder(ResultSet rs)throws Exception;

}

javabeanlist的编写

javabeanlist.java

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;

import org.omg.CORBA.PRIVATE_MEMBER;

public class javabeanlist<T>implements type<List<T>> {

    private Class<T>classtype;

    public javabeanlist(Class<T>classtype) {

        this.classtype=classtype;

    }

    @Override

    public List<T> hanlder(ResultSet rs) throws Exception {

        // TODO Auto-generated method stub

        

        

        List<T>list=new ArrayList<>();

        while(rs.next())

        {

               T obj=classtype.newInstance();

               BeanInfo beanInfo=Introspector.getBeanInfo(classtype,Object.class);

               PropertyDescriptor[] pro=beanInfo.getPropertyDescriptors();

               for(PropertyDescriptor ps:pro)

               {

                   String name=ps.getName();

                   Object value=rs.getObject(name);

                   ps.getWriteMethod().invoke(obj, value);

               }

               list.add(obj) ;

        }

        return list;

    }

}

Javabean的编写

javabean.java

package download_upload.javabean;

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.sql.ResultSet;

public class javabean<T> implements type<T>{

    private  Class<T>classtype;

    public javabean(Class<T>classtype) {

        // TODO Auto-generated constructor stub

        this.classtype=classtype;

    }

    @Override

    public T hanlder(ResultSet rs) throws Exception {

        // TODO Auto-generated method stub

        if(rs.next())

        {

               T obj=classtype.newInstance();

               BeanInfo beanInfo=Introspector.getBeanInfo(classtype,Object.class);

               PropertyDescriptor[] pro=beanInfo.getPropertyDescriptors();

               for(PropertyDescriptor ps:pro)

               {

                String name=ps.getName();

                Object value=rs.getObject(name);

                ps.getWriteMethod().invoke(obj, value);

               }

               return obj;

        }

        return null;

    }

}

模板类的编写

template.java

package download_upload.template;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import download_upload.javabean.type;

import download_upload.utils.utils;

/*DML操作*/

public class template {

    public static int DMLoperator(String sql,Object...param) {

        Connection conn=utils.conn();

        PreparedStatement ps=null;

        try {

            ps=conn.prepareStatement(sql);

            for(int i=0;i<param.length;i++) {

                ps.setObject(i+1,param[i]);

            }

            return ps.executeUpdate();

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally {

            utils.close(conn,ps,null);

        }

        return 0;

    }

/*DQL操作*/

    public static <T>T  DQLoperator(String sql,type<T> type,Object...para){

        Connection conn=utils.conn();

        PreparedStatement ps=null;

        ResultSet re=null;

        try {

            ps=conn.prepareStatement(sql);

            for(int i=0;i<para.length;i++) {

            ps.setObject(i+1, para[i]);

            }

            re=ps.executeQuery();

            return type.hanlder(re);

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally {

            utils.close(conn, ps, re);

        }

        return null;

    }

}

utils工具类

utils.java

package download_upload.utils;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class utils {

    private static DataSource datasource;

    static{

        Properties pro=new Properties();

        ClassLoader cla=Thread.currentThread().getContextClassLoader();

        InputStream in=cla.getResourceAsStream("db.properties");

        try {

            pro.load(in);

            Class.forName(pro.getProperty("driverClassName"));

            datasource=DruidDataSourceFactory.createDataSource(pro);

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    public static Connection conn() {

        try {

            return datasource.getConnection();

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            throw new RuntimeException("数据库连接异常");

        }

    }

    public static void close(Connection conn,Statement st,ResultSet re) {

         try {

               if(re!=null)

                    re.close();

            } catch (Exception e2) {

                // TODO: handle exception

                e2.printStackTrace();

            }

            finally {

                    try {

                        if(st!=null)

                            st.close();

                    } catch (Exception e3) {

                        // TODO: handle exception

                        e3.printStackTrace();

                    }finally {

                        try {

                            if(conn!=null)

                                conn.close();

                        } catch (Exception e4) {

                            // TODO: handle exception

                            e4.printStackTrace();

                        }

                    }

            }

    }

}

webutils工具类

webutils.java

package download_upload.servlet;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Date;

import java.util.List;

import java.util.UUID;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadBase;

import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import download_upload.domian.file;

public class webutils {

    public static file doFileUpload(HttpServletRequest req) throws FileSizeLimitExceededException {

        file fud = new file();// 文件信息对象

        try {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 临时文件夹temp

            factory.setRepository(new File(req.getSession().getServletContext().getContextPath()+"/temp"));

//            factory.setRepository(new File("/temp"));// 临时文件夹temp

            factory.setSizeThreshold(1024 * 1024);// 临时缓冲区大小为1M

            ServletFileUpload parse = new ServletFileUpload(factory);// 解析器

            //上传文件大小

            parse.setFileSizeMax(1024 * 1024 * 2);// 单个文件大小限制为2M

            parse.setSizeMax(1024 * 1024 * 20);// 总的文件大小限制为20M

            //解决中文文件名的乱码

            parse.setHeaderEncoding("utf-8");

            List<FileItem> list = parse.parseRequest(req);

            for (FileItem fileItem : list) {

                // 普通表单

                if (fileItem.isFormField()) {

                    String fieldName = fileItem.getFieldName();

                    // String value = fileItem.getString();

                    String value = fileItem.getString("utf-8");// 解决字段的中文乱码问题

                    System.out.println("fieldName:" + fieldName);

                    System.out.println("value:" + value);

                    // 将当前字段封装到fud对象中对应的字段中去

                    

                    //普通字段都通过这个保存到fud中

                    BeanUtils.setProperty(fud, fieldName, value);

                }

                // 文件

                else {

                    String filename = fileItem.getName();// 获取文件名

                

                    //文件名:aa.txt 与c:\a\b\c\aa.txt的处理 统一

                    int index=filename.lastIndexOf("\\");

                    if(index!=-1){

                        filename=filename.substring(index+1);

                    }

                    String realPath=req.getSession().getServletContext().getRealPath("/wenjian/upload");

                    

                    //生成随机文件夹

                    String savePath=generateSavePath(realPath,filename);

                    

                    //生成唯一的文件名

                    String uuidname=generateUUIDName(filename);

                    

                    // 上传文件

                    InputStream in = fileItem.getInputStream();// 获取文件读取流

//                    OutputStream out = new FileOutputStream("d:/" + name);

                    //保存文件夹:savePath  唯一文件名:uuidname

                    OutputStream out = new FileOutputStream(new File(savePath,uuidname));

                    byte[] buf = new byte[1024];

                    int len = 0;

                    while ((len = in.read(buf)) != -1) {

                        out.write(buf, 0, len);

                    }

                    in.close();

                    out.close();

                    //删除临时文件

                    fileItem.delete();

                    

                    fud.setFilename(filename);//文件名

                    fud.setUuidname(uuidname);//唯一文件名

                    fud.setSavepath(savePath);//保存路径

                    fud.setUploadtime(new Date().toLocaleString());

                }

            }

            return fud;//返回文件信息封装对象

        } catch (FileUploadBase.FileSizeLimitExceededException e) {

//            e.printStackTrace();//仅仅只是打印异常错误信息

            

            //使用失败,因为此处并没有response

//            request.setAttribute("message", "对不起,您上传的文件大小超过了大小的限制");

//            request.getRequestDispatcher("/message.jsp").forward(request,response);

        

            //怎么办?

            //抛出一个异常出去  实际上异常也是一个返回值

            //抛异常【编译时异常  还是   运行时异常】

            //编译时异常

            throw e;//记得抛出异常要在方法中进行声明

        }

        catch(Exception e){

            throw new RuntimeException(e);//抛出运行时异常

        }

    }

    //生成唯一的文件名

    private static String generateUUIDName(String filename) {

        return UUID.randomUUID().toString()+"_"+filename;

    }

    //生成随机文件夹

    private static String generateSavePath(String realPath, String filename) {

        int hashCode=filename.hashCode();

        //通过位运算,计算出一级和二级目录的数字

        int first=hashCode & (0xf);//以及目录

        int second=(hashCode>>4)&(0xf);//二级目录

        String savePath=realPath+"/"+first+"/"+second;

        File f=new File(savePath);

        if(!f.exists()){

            f.mkdirs();//创建多级目录

        }

        return savePath;//保存路径

    

    }

}

DAO设计模式

ifile.java

package download_upload.impl.filedao;

import java.util.List;

import download_upload.domian.file;

public interface Ifile {

    public void insert(file fud);//上传文件

    

    public List<file> list();//查询文件

    public file select(Long id);//通过id获得文件的全部信息

}

fileimpl.java

package download_upload.impl;

import java.util.List;

import download_upload.javabean.javabean;

import download_upload.javabean.javabeanlist;

import download_upload.domian.file;

import download_upload.impl.filedao.Ifile;

import download_upload.template.template;

public class fileimpl implements Ifile{

    @Override

    public void insert(file fud) {

        // TODO Auto-generated method stub

        String sql="INSERT INTO baocun (uuidname,filename,savepath,uploadtime,description,username)VALUES(?,?,?,?,?,?)";

        template.DMLoperator(sql, fud.getUuidname(),fud.getFilename(),fud.getSavepath(),fud.getUploadtime(),fud.getDescription(),fud.getUsername());

    }

    @Override

    public List<file> list() {

        // TODO Auto-generated method stub

        String sql="SELECT *FROM baocun";

        return template.DQLoperator(sql, new javabeanlist<>(file.class));

    }

    @Override

    public file select(Long id) {

        // TODO Auto-generated method stub

        String sql="SELECT *FROM baocun where id=?";

        return  template.DQLoperator(sql, new javabean<>(file.class),id);

    }

}

db.properties

#key=value

driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/upload?rewriteBatchedStatements=true

username=root

password=123456

maxActive=5

servlet的编写

down.java

package download_upload.servlet;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

importjava.net.URLEncoder;

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 download_upload.domian.file;

import download_upload.impl.fileimpl;

import download_upload.impl.filedao.Ifile;

@WebServlet("/download")

public class down extends HttpServlet{

    /**

     *

     */

    private Ifile ifile;

    private static final long serialVersionUID = 1L;

    @Override

    public void init() throws ServletException {

        // TODO Auto-generated method stub

        ifile=new fileimpl();

    }

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO Auto-generated method stub

        String id = req.getParameter("id");

        

        file fud=ifile.select(Long.valueOf(id));//通过id获取文件相关信息

        

        String path=fud.getSavepath();//保存路径

        String uuidname=fud.getUuidname();//保存文件名

        File f=new File(path,uuidname);//要下载的文件的存放位置    path/name

        //健壮性判断

        if(!f.exists()){

            req.setAttribute("message", "对不起,当前文件已删除");

            req.getRequestDispatcher("/message.jsp").forward(req, resp);

            

        }

        

        //将中文的文件名编码后再放到http的响应头中去,编码之后浏览器收到后会自动解码

        String filename=URLEncoder.encode(fud.getFilename(),"utf-8");

        

        //设置参数,使得浏览器可以以下载的方式打开文件。

        resp.setHeader("content-disposition", "attachement;filename="+filename);

        //将要下载的文件当做一个inputStream读取进来

        InputStream in=new FileInputStream(f);

        //读进来后,再写到response.getOutputStream()去就可以了

        //相应的数据

        OutputStream out=resp.getOutputStream();

        

        byte[] buf=new byte[1024];

        int len=0;

        while((len=in.read(buf))!=-1){

            out.write(buf, 0, len);

            System.out.println(buf);

            System.out.println(len);

        }

        in.close();

        out.close();

        System.out.println("下载文件成功");

    }

}

 downtown.java

package download_upload.servlet;

import java.io.IOException;

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 download_upload.impl.fileimpl;

import download_upload.impl.filedao.Ifile;

@WebServlet("/listfile")

public class download extends HttpServlet{

    private Ifile file;

    @Override

    public void init() throws ServletException {

        // TODO Auto-generated method stub

        file=new fileimpl();

    }

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO Auto-generated method stub

        List list=file.list();

        

        req.setAttribute("list", list);

        req.getRequestDispatcher("/list.jsp").forward(req, resp);

    }

}

 upload.java

package download_upload.servlet;

import java.io.IOException;

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.fileupload.servlet.ServletFileUpload;

import download_upload.domian.file;

import download_upload.impl.fileimpl;

import download_upload.impl.filedao.Ifile;

import net.sf.json.util.WebUtils;

@WebServlet("/upload")

public class upload extends HttpServlet{

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO Auto-generated method stub

        if (!ServletFileUpload.isMultipartContent(req)) {

            req.setAttribute("message", "不是请求的信息表单,请确认表单属性是否正确");

            req.getRequestDispatcher("/message.jsp").forward(req,resp);

            return;

        }

        

        try {

            //调用工具类,获得上传文件信息

            file fud=webutils.doFileUpload(req);

            Ifile wenjian=new fileimpl();

            wenjian.insert(fud);

            req.setAttribute("message", "上传文件成功");

            req.getRequestDispatcher("/message.jsp").forward(req,resp);

        

        

        } catch (Exception e) {

            req.setAttribute("message", "对不起,您上传的文件大小超过了大小的限制");

            req.getRequestDispatcher("/message.jsp").forward(req,resp);

        }

    }

}

猜你喜欢

转载自blog.csdn.net/zhouzhou_98/article/details/83115625
今日推荐