Java教程

【无标题】javaweb文件上传与下载

本文主要是介绍【无标题】javaweb文件上传与下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

构建数据库filetest:包含文件名称及路径

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for file
-- ----------------------------
DROP TABLE IF EXISTS `file`;
CREATE TABLE `file` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `filename` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `filepath` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of file
-- ----------------------------

项目目录结构:

文件上传页面index.jsp:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <title>文件上传与下载</title>
<%--  使用cnd加速--%>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <%
    String proPath = request.getServletContext().getContextPath();
  %>
  <script type="text/javascript">
<%--    设置input宽度--%>
    $(function (){
      $("[type=file]").each(function (){
        $(this).css("width","150px");
      })
    })
    function toDown(){
      window.location.href = '<%=proPath %>/filelist';
    }
  </script>
</head>
<body>
<form action="<%=proPath %>/upfile" method="post" enctype="multipart/form-data">
  文件1:<input type="file" name="file1"/><br/>
  文件2:<input type="file" name="file2"/><br/>
  文件3:<input type="file" name="file3"/><br/>
  <input type="submit" value="上传">
  <div style="color: red;">${requestScope.msg}</div>
</form>
<button type="button" onclick="toDown();">去下载</button>
</body>
</html>

文件列表页面filelist.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>文件列表</title>
    <%
//        String path = request.getContextPath();
//        String proPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
        String proPath = request.getServletContext().getContextPath();
    %>
</head>
<body>
<c:forEach var="file" items="${requestScope.filelist}">
    文件名:<c:out value="${file.filename}"/>&nbsp;&nbsp;
    <a href="<%=proPath %>/downfile?id=<c:out value="${file.id}"/>&filename=<c:out value="${file.filename}"/>">下载</a><br>
</c:forEach>
<font>${requestScope.msg}</font>
</body>
</html>

javabean:

package com.web.beans;

public class FileTest {
    private int id;
    private String filename;
    private String filepath;

    public FileTest() {
    }

    public FileTest(int id,String filename, String filepath) {
        this.id = id;
        this.filename = filename;
        this.filepath = filepath;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getFilepath() {
        return filepath;
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    @Override
    public String toString() {
        return "FileTest{" +
                "id=" + id +
                ", filename='" + filename + '\'' +
                ", filepath='" + filepath + '\'' +
                '}';
    }
}

c3p0配置:

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <named-config name="test">
        <property name="user">root</property>
        <property name="password">fuyou</property>
        <property name="jdbcUrl">jdbc:mysql://119.91.83.99:3306/filetest?characterEncoding=UTF-8</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
<!--        连接不够时的增长-->
        <property name="acquireIncrement">5</property>
        <!-- 初始化数据库连接池时连接的数量 -->
        <property name="initialPoolSize">20</property>
        <!-- 数据库连接池中的最大的数据库连接数 -->
        <property name="maxPoolSize">25</property>
        <!-- 数据库连接池中的最小的数据库连接数 -->
        <property name="minPoolSize">5</property>
    </named-config>
</c3p0-config>

数据库连接:

package com.web.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 创建时间 2021/11/25
 * 描述:jdbc
 * @author 鄢富友
 */
public class BaseDao {
    private static PreparedStatement ps;
    private static ResultSet rs;
    private static ComboPooledDataSource dspool;
    static Connection conn = null;
    static {
        dspool = new ComboPooledDataSource("test");
    }
    public Connection getConn(){
        try{
            conn = dspool.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    public void closeAll(ResultSet rs,PreparedStatement ps,Connection conn){
            if (rs != null){
                try {
                    rs.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (ps != null){
                try {
                    ps.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                if (conn != null){
                    try {
                        conn.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
    }
}

数据库交互的接口:

package com.web.dao;

import com.web.beans.FileTest;

import java.util.List;

public interface FileService {
    int addFile(FileTest file_bean);
    List<FileTest> fileList();
    String getfilepath(String id);
}

接口实现:

package com.web.dao.impl;

import com.web.beans.FileTest;
import com.web.dao.FileService;
import com.web.jdbc.BaseDao;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建时间 2021/11/25
 * 描述:
 */
public class FileServiceImpl implements FileService {
    static BaseDao dao = new BaseDao();
    private static PreparedStatement ps;
    private static ResultSet rs;
    static Connection conn = null;
    @Override
    public int addFile(FileTest file_bean) {
        int i = 0;
        String sql ="insert into file(filename,filepath) values(?,?);";
        try {
            conn = dao.getConn();
            ps = conn.prepareStatement(sql);
            ps.setObject(1,file_bean.getFilename());
            ps.setObject(2,file_bean.getFilepath());
            i = ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dao.closeAll(rs,ps,conn);
        }
        return i;
    }

    @Override
    public List<FileTest> fileList() {
        String sql = "select * from file;";
        List<FileTest> file_list = new ArrayList<>();
        try{
            conn = dao.getConn();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                FileTest oneFile = new FileTest(Integer.parseInt(rs.getString("id")),rs.getString("filename"),rs.getString("filepath"));
                file_list.add(oneFile);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dao.closeAll(rs,ps,conn);
        }
        return file_list;
    }

    @Override
    public String getfilepath(String id) {
        String filepath = null;
        String sql = "select filepath from file where id=?;";
        try{
            conn = dao.getConn();
            ps = conn.prepareStatement(sql);
            ps.setObject(1,id);
            rs = ps.executeQuery();
            while (rs.next()){
                filepath = rs.getString("filepath");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            dao.closeAll(rs,ps,conn);
        }
        return filepath;
    }
}

文件上传的servlet:

package com.web.Servlet;

import com.web.beans.FileTest;
import com.web.dao.impl.FileServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 创建时间 2021/11/25
 * 描述:上传
 * @author 鄢富友
 */
@WebServlet("/upfile")
public class UpServlet extends HttpServlet {
    private static FileServiceImpl fileService = new FileServiceImpl();
    protected void doGet(HttpServletRequest req, HttpServletResponse res){
        String savePath = this.getServletContext().getRealPath("/WEB-INF/upload/");
        File path = new File(savePath);
//        获取时间戳防止文件覆盖
        Long startTs = System.currentTimeMillis();
        if (!path.exists() && !path.isDirectory()){
            path.mkdirs();
        }
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload up = new ServletFileUpload(factory);
            up.setHeaderEncoding("UTF-8");
            if (!ServletFileUpload.isMultipartContent(req)){
                return;
            }
            List<FileItem> file_list = up.parseRequest(req);
            FileTest test_file = new FileTest();
            int file_num = 0;
            for (FileItem onefile : file_list){
                if (!onefile.isFormField()){
                    String filename = onefile.getName();
                    if (filename == null || filename.trim().equals("")){
                        System.out.println("未选择文件!");
                        continue;
                    }
                    System.out.println(savePath+filename);
                    file_num ++;
                    test_file.setFilename(filename);
                    test_file.setFilepath(savePath+filename);
                    String filepath = savePath+filename;
                    InputStream in = onefile.getInputStream();
                    OutputStream out = new FileOutputStream(filepath);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = in.read(bytes)) != -1){
                        out.write(bytes,0,len);
                    }
                    in.close();
                    out.close();
                    onefile.delete();
                    System.out.println(test_file);
                    fileService.addFile(test_file);
                }
            }
            req.setAttribute("msg","上传成功!" + file_num + "个");
            req.getRequestDispatcher("/index.jsp").forward(req,res);
            return;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    protected void doPost(HttpServletRequest req,HttpServletResponse res){
        doGet(req, res);
    }
}

文件列表的servlet:

package com.web.Servlet;

import com.web.beans.FileTest;
import com.web.dao.impl.FileServiceImpl;

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 java.io.IOException;
import java.util.List;

/**
 * 创建时间 2021/11/26
 * 描述:文件列表
 * @author 鄢富友
 */
@WebServlet("/filelist")
public class FileListServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        FileServiceImpl fileService = new FileServiceImpl();
        List<FileTest> fileList = fileService.fileList();
        req.setAttribute("filelist",fileList);
        req.getRequestDispatcher("/filelist.jsp").forward(req,res);
        return;
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
}

文件下载的servlet:

package com.web.Servlet;

import com.web.dao.impl.FileServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 创建时间 2021/11/25
 * 描述:下载
 * @author 鄢富友
 */
@WebServlet("/downfile")
public class DownServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res){
//        文件路径
        String filename = req.getParameter("filename");
        String id = req.getParameter("id");
        FileServiceImpl fileService = new FileServiceImpl();
        String filepath = fileService.getfilepath(id);
        System.out.println(filename+"  "+filepath);
        res.setContentType("text/html;charset=UTF-8");
        try {
            if (filepath == null){
                req.setAttribute("msg","参数错误!");
                req.getRequestDispatcher("/filelist.jsp").forward(req,res);
                return;
            }
            File file = new File(filepath);
            if (!file.exists()){
                req.setAttribute("msg","文件不存在!");
                req.getRequestDispatcher("/filelist.jsp").forward(req,res);
                return;
            }
            res.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
            res.setContentType("multipart/form-data");
            FileInputStream in = new FileInputStream(filepath);
            OutputStream out = res.getOutputStream();
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = in.read()) != -1){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void doPost(HttpServletRequest req, HttpServletResponse res){
        doGet(req,res);
    }
}

今日份收工。

这篇关于【无标题】javaweb文件上传与下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!