在使用JSP和Servlet Java将上传文件的数据(二进制)插入到MS SQL数据库之前,将其转换为String

时间:2014-07-16 07:52:31

标签: sql-server jsp servlets upload

我正在关注http://www.codejava.net/coding/upload-files-to-database-servlet-jsp-mysql中的代码。我修改了一些代码,现在正在运行。我现在的问题是,我还添加了“select * from contact”来查看上传文件的值,但是其字段中存储的值是二进制格式(数据库中的数据类型是varbinary)

是否可以将二进制数据转换为String,这样当它存储在数据库中时,该值已经是String格式?当我执行“select * from contact”时,显示的字段的值将采用String格式?

FileUploadDB.java

package com.process.web.controller;

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("/fileuploaddb.html")
@MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
}

private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";

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

            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());
                //DriverManager.getConnection(dbURL);
                //com.microsoft.sqlserver.jdbc.Driver

                Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
                if(conn!=null) {
                    System.out.println("Connection Successful!");
                } else {
                    System.out.println("Error in Connection");
                }
                // constructs SQL statement
                String sql = "INSERT INTO contact (firstname, lastname, 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.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));                     

                }

                // 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();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.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);
            }
        }
        }

这是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="fileuploaddb.html" 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>


**This is the 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">
<html>
<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>

1 个答案:

答案 0 :(得分:1)

AbstractMethodError意味着你的JDBC驱动程序的PreparedStatements没有实现

setBlob(int, InputStream).

刚刚看到你正在使用的驱动程序,并且根据它没有采取的文档

`setBlob(int, InputStream)`

但需要

setBlob(int parameterIndex, java.sql.Blob x) 

请阅读此文档http://jtds.sourceforge.net/doc/net/sourceforge/jtds/jdbc/JtdsPreparedStatement.html以获取进一步的帮助,否则我建议您更改正在使用的驱动程序。

请参阅此SO post