java - 使用 jsp 和 servlet 将文件存储在 MySql 数据库中。

标签 java mysql jsp servlets

我正在尝试使用 jsp 和 servlet 将文件(文本或图像)存储在 mySql 数据库中。

这是 index.jsp。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
    <h1>File Upload to Database Demo</h1>
    <form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
        <table border="0">
            <tr>
                <td>First Name: </td>
                <td><input type="text" name="firstName" size="50"/></td>
            </tr>
            <tr>
                <td>Last Name: </td>
                <td><input type="text" name="lastName" size="50"/></td>
            </tr>
            <tr>
                <td>Portrait Photo: </td>
                <td><input type="file" name="photo" size="50"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Save">
                </td>
            </tr>
        </table>
    </form>
</center>
</body>
</html>
  1. 这是我的 FileUploadDBServlet。

    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    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(name = "FileUploadDBServlet", urlPatterns ={"/FileUploadDBServlet"})          
    public class FileUploadDBServlet extends HttpServlet {
    
       // database connection settings
         String dbURL = "jdbc:mysql://localhost:3306/rep";
          String dbUser = "root";
          String dbPass = "";
    
        protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // gets values of text fields
        String firstName = request.getParameter("firstName");
       String lastName = request.getParameter("lastName");
    
       InputStream inputStream=null; // input stream of the upload file
    
    // obtains the upload file part in this multipart request
    Part filePart = request.getPart("photo");
    if (filePart != null) {
        // prints out some information for debugging
        System.out.println(filePart.getName());
        System.out.println(filePart.getSize());
        System.out.println(filePart.getContentType());
    
      // obtains input stream of the upload file
         inputStream = filePart.getInputStream();
    
    }
     //System.out.println(inputStream);
    Connection conn = null; // connection to the database
    String message = null;  // message will be sent back to client
    
    try {
        // connects to the database
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
    
        // constructs SQL statement
        String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
        PreparedStatement statement = conn.prepareStatement(sql);
    
        statement.setString(1, firstName);
        statement.setString(2, lastName);
    
       if (inputStream != null) {
            // fetches input stream of the upload file for the blob column
            statement.setBlob(3, inputStream);
       }
    
        // sends the statement to the database server
        int row = statement.executeUpdate();
        if (row > 0) {
            message = "File uploaded and saved into database";
        }
    } catch (SQLException ex) {
        message = "ERROR: " + ex.getMessage();
        ex.printStackTrace();
    } finally {
        if (conn != null) {
            // closes the database connection
            try {
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        // sets the message in request scope
        request.setAttribute("Message", message);
    
        // forwards to the message page
        getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
    }
    }
    }
    
  2. 这是我的 Message.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd"/>
    
     <head>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
     <title>Message</title>
     </head>
     <body>
     <center>
          <h3><%=request.getAttribute("Message")%></h3>
     </center>
     </body>
     </html>
    

消息页面显示“错误:没有为参数 3 指定值”。 所以,我认为 null 值存储在 inputStream 中。为什么会这样,如何处理? 谢谢。

最佳答案

如果您的输入流为空,您可以使用 statement.setNull(3, java.sql.Types.BLOB);

if (inputStream != null) {
    // fetches input stream of the upload file for the blob column
    statement.setBlob(3, inputStream);
} else {
    statement.setNull(3, java.sql.Types.BLOB);
}

关于java - 使用 jsp 和 servlet 将文件存储在 MySql 数据库中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29620451/

相关文章:

mysql - 从数据库调用后,我的 Base64 图像以不同的格式返回

mysql 在查询中获取空闲点

mysql - 如果不为 NULL,则选择列,然后选择其他

java - 改进代码以保存到数据库

html - 将 CSS 文件链接到 JSP 的问题

java - 我需要一些帮助,用 java 读取 WAV 文件并确定其各种幅度

java - Java 数组

java - 如何向 URLStreamHandler 提供上下文?

javascript - Javascript 中的 onkeypress + onblur

java - JAXB 在 writeTo 方法中写入 OutputStream