栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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");
%>

 

    
        
        View Uploads
    
    
 
        <%@page import="com.example.*,java.util.*"%>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
        Uploads List
 
        <%
            List list = UploadDAO.listAllUploads();
            request.setAttribute("list", list);
        %>
 
        
                
视屏名称 路径 操作
${u.getId()} ${u.getFilename()} 下载

再次添加

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");
%>
 
 

 

    
        文件上传到数据库
        
    
    
        
视屏名称
路径

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("
您已经成功上传视频
前往查看"); } catch (FileNotFoundException fnf) { writer.println("You did not specify a file to upload"); writer.println("
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 listAllUploads() throws SQLException {
        List 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;
 

@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();
 
    }
 
    
    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博客

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/878586.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号