Bootstrap

Java+Jsp+Servlet+Mysql 文件、图片、视屏上传数据库并且下载查看

项目系统要求:(Tomcat 8.0 Eclipse JEE Mysql 5.0)

项目效果展示:

运行fileupload.jsp,输入上传文件类型,选择文件。

 点击上传后跳至添加成功界面,点击前往查看。

查看界面,点击下载即可查看内容:

 数据库中同样插入了信息。

项目代码结构如下:

1、数据库代码:

CREATE TABLE `upload` (
	`id` VARCHAR(50) NOT NULL DEFAULT '' COLLATE 'utf8mb4_unicode_ci',
	`file` LONGBLOB NOT NULL,
	`filename` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb4_unicode_ci',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;

2、 index.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
%>
<!DOCTYPE html>
 
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>View Uploads</title>
    </head>
    <body>
 
        <%@page import="com.example.*,java.util.*"%>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
        <h1>Uploads List</h1>
 
        <%
            List<Upload> list = UploadDAO.listAllUploads();
            request.setAttribute("list", list);
        %>
 
        <table border="1" width="90%">
            <tr>
                <th>视屏名称</th>
                <th>路径</th>
                <th>操作</th>
 
            </tr>
            <c:forEach items="${list}" var="u">
                <tr>
                    <td>${u.getId()}</td>
                    <td>${u.getFilename()}</td>
                    <td><a href="DBFileDownload?id=${u.getId()}">下载</a></td>
                </tr>
            </c:forEach>
        </table>
        <br />
        <a href="fileupload.jsp">再次添加</a>
 
    </body>
</html>

3、fileupload.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
%>
 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <title>文件上传到数据库</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="FileUpload" enctype="multipart/form-data" >
			<table>
        		<tr><td>视屏名称</td>
        			<td><input type="text" name="id" /></td>
        		<tr>
        			<td>路径</td>
           			<td><input type="file" name="file" id="file" /> </td>
        		</tr>
        		<tr>
        	<td colspan="2">
            	<input type="submit" value="添加" name="upload" id="upload" /> </td>
        	</tr>
   	</table>
    </form>
   </body>
</html>

4、FileUpload.java

//中文
package com.example;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@WebServlet("/FileUpload")
@MultipartConfig
public class FileUpload extends HttpServlet {
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
 
        final Part filePart = request.getPart("file");
        String id = request.getParameter("id");
 
        InputStream FileBytes = null;
        final PrintWriter writer = response.getWriter();
        Connection con = null;
        Statement stmt = null;
 
        try {
            String filename = filePart.getSubmittedFileName();
            FileBytes = filePart.getInputStream(); // to get the body of the request as binary data
 
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/file?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "123456");
            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
            int success = 0;
            PreparedStatement pstmt = con.prepareStatement("INSERT INTO upload VALUES(?,?,?)");
            pstmt.setString(1, id);
            pstmt.setBinaryStream(2, FileBytes); //Storing binary data in blob field.
            pstmt.setString(3, filename); //Storing binary data in blob field.
            success = pstmt.executeUpdate();
            if (success >= 1) {
                System.out.println("Data Stored");
            }
            con.close();
 
            writer.println("<br/> 您已经成功上传视频<br/><a href='.'>前往查看</a>");
 
        } catch (FileNotFoundException fnf) {
            writer.println("You  did not specify a file to upload");
            writer.println("<br/> ERROR: " + fnf.getMessage());
 
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (con != null) {
                // closes the database connection
                try {
                    con.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
 
            if (FileBytes != null) {
                FileBytes.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
 
    }
 
}

5、Upload.java

package com.example;
 
public class Upload {
 
    private String id;
    private String filename;
 
    public Upload() {
    }
 
    public Upload(String id, String filename) {
        this.id = id;
        this.filename = filename;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getFilename() {
        return filename;
    }
 
    public void setFilename(String filename) {
        this.filename = filename;
    }
 
}

6、UploadDao

package com.example;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
public class UploadDAO {
 
    public static Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/file?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
                    "root", 
                    "123456");
        } catch (Exception e) {
            System.out.println(e);
        }
        return con;
    }
 
    public static List<Upload> listAllUploads() throws SQLException {
        List<Upload> listUpload = new ArrayList<>();
 
        String sql = "SELECT id,filename FROM upload";
 
        Connection jdbcConnection = getConnection();
 
        Statement statement = jdbcConnection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
 
        while (resultSet.next()) {
 
            String id = resultSet.getString("id");
            String filename = resultSet.getString("filename");
 
            Upload upload = new Upload(id, filename);
            listUpload.add(upload);
        }
 
        resultSet.close();
        statement.close();
 
        jdbcConnection.close();
 
        return listUpload;
    }
 
}

7、DBFileDownloadServlet.java

//中文
package com.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import java.net.URLEncoder;
import java.io.InputStream;
 
/**
 * Servlet implementation class GetDetails
 */
@WebServlet("/DBFileDownload")
public class DBFileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String id = request.getParameter("id") != null ? request.getParameter("id") : "NA";
        ServletOutputStream sos;
        Connection con = null;
        PreparedStatement pstmt = null;
        sos = response.getOutputStream();
        ResultSet rset = null;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/file?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "123456");
            } catch (Exception e) {
                System.out.println(e);
                System.exit(0);
            }
            pstmt = con.prepareStatement("Select file,filename from upload where id=?");
            System.out.println("Select file,filename from upload where id=" + id.trim());
            pstmt.setString(1, id.trim());
            rset = pstmt.executeQuery();
            if (rset.next()) {
                response.setContentType("APPLICATION/OCTET-STREAM");
 
                response.setHeader("Content-disposition", "inline; filename*=UTF-8''" + URLEncoder.encode(rset.getString("filename"), "UTF-8"));
 
                InputStream inputStream = rset.getBinaryStream("file");
 
                int i;
                while ((i = inputStream.read()) != -1) {
                    sos.write(i);
                }
 
                System.out.println(rset.getBytes("file"));
                System.out.println(rset.getString("filename"));
            } else
                return;
 
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (con != null) {
                // closes the database connection
                try {
                    con.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
 
        }
 
        sos.flush();
        sos.close();
 
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
 
}

8、项目中用过的包: 

若数据库系统不支持插入较大文件,(You can change this value on the server by setting the max_allowed_packet' variable.)

请参考连接: 解决Mysql You can change this value on the server by setting the max_allowed_packet' variable. 异常_马丁半只瞄的博客-CSDN博客

项目资料包可私信联系小白博主(QQ:2250435858) 

;