0

我是 jsp 的新手,我正在尝试创建一个简单的页面,用户可以在其中将照片上传到数据库。

我使用了一个 upload.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">
<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="uploadServlet" 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>

还有一个 java 类来完成这项工作:

package classes.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

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("/uploadServlet")
@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {

    // database connection settings
  static final String ODBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
  static final String DSN = "jdbc:odbc:PMRteste";
  static final String USER = "root";
  static final String PWD = "1234";


    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");
        Connection _conexao = null;

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



        //Connection conn = null; // connection to the database
        String message = null;  // message will be sent back to client

        try {
                    try {
                try {
                    // connects to the database
                    //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                    Class.forName(ODBC_DRIVER).newInstance();
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(FileUploadDBServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                    } catch (InstantiationException ex) {
                        Logger.getLogger(FileUploadDBServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IllegalAccessException ex) {
                        Logger.getLogger(FileUploadDBServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
            _conexao = DriverManager.getConnection(DSN, USER, PWD);

            // constructs SQL statement
            String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
            //System.out.append("INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)");
            PreparedStatement statement = _conexao.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.setBinaryStream(3, inputStream);
                //System.out.println("entra aqui");
            }
            // 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 (_conexao != null) {
                // closes the database connection
                try {
                    _conexao.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);
        }
    }
}

但我总是收到错误消息:[MySQL][ODBC 5.2(a) Driver][mysqld-5.6.14]SQLBindParameter not used for all parameters

我检查了与数据库的连接,一切正常(我可以在数据库中添加名称和姓氏)。

(message.jsp 仅在照片是否成功更新时向用户显示消息)

你能帮助我吗?:)

4

2 回答 2

0

问题是 ODBC-JDBC 桥。当我使用 MySQL 驱动程序时,它运行良好!

感谢尼科斯的提示!

于 2013-12-02T21:33:06.473 回答
0

这不是答案,但必须先...

不要在 Servlet 中共享非静态成员变量!(我在看着你_conexao

应用服务器完全可以创建 1 个此类的实例来服务所有请求;如果一个请求到达而另一个请求正在被处理,该_conexao字段将被覆盖并且会发生不可预知的行为(虚假异常、泄漏的连接以及谁知道还有什么)。幸运的是,这可以在您的代码中轻松解决,只需创建_conexao一个局部变量doPost().


尝试实际回答:这可能是由BufferedReader消耗 的相关代码引起的InputStream,因此将其设置PreparedStatement为 不提供数据。您是否尝试省略此代码?此外,您正在关闭BufferedReader( in.close()) 我相信这也会关闭基础资源,即InputStream.


还有另一个与问题无关的建议:除非有充分的理由,否则我会使用 MySQL 驱动程序,而不是 ODBC。

抱歉,如果您需要更多帮助,我愿意与您交谈!祝你好运!

于 2013-12-02T12:51:42.923 回答