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) 

  • 1
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件路径存储到 MySQL 数据库中,可以通过以下步骤实现: 1. 在 MySQL 数据库中创建一个表,用于存储文件路径和其他相关信息。 2. 在 JSP 页面中,创建一个表单,用于上传文件。在表单中,需要设置 enctype="multipart/form-data" 属性,以便支持文件上传。 3. 在 Servlet 中,使用 Apache Commons FileUpload 库来解析上传文件,并将文件保存到服务器的指定路径中。同时,将文件路径和其他相关信息插入到 MySQL 数据库中。 以下是示例代码: JSP 页面: ``` <form action="uploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="text" name="filename" /> <input type="submit" value="Upload" /> </form> ``` Servlet 代码: ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); String filePath = "C:/uploads/" + filename; File file = new File(filePath); // 使用 Apache Commons FileUpload 库解析上传文件 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); // 保存文件到服务器指定路径 for (FileItem item : items) { if (!item.isFormField()) { item.write(file); } } // 将文件路径和其他相关信息插入到 MySQL 数据库中 String sql = "INSERT INTO files (filename, filepath) VALUES (?, ?)"; try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, filename); pstmt.setString(2, filePath); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } ``` 注意:这只是一个简单的示例,实际开发中还需要进行错误处理和安全性检查。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值