java - ImageIO.read 在字节数组上返回 null

标签 java web-services jersey javax.imageio

这是我的代码。我从我的数据库中得到一个 blob。像这样返回给我:java.io.BufferedInputStream@16e31e37。现在我试图在浏览器中显示来 self 的 servlet 的图像,但是我的 BufferedImage 图像始终为空。我调试了它并注意到我的 blob 长度始终为 34.. 不管图像如何。

@Path("/photo" )
public class DisplayPhoto { 

@GET
@Path("{id}")
 @Produces("image/*")
public Response post(@PathParam("id") String id) throws IOException {
    Connection con = connection();
    Blob blob = getPhoto(con);




    int blobLength = 0;
    try {
        blobLength = (int) blob.length();
    } catch (SQLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }  
    byte[] data = null;
    try {
        data = blob.getBytes(1, blobLength);
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    BufferedImage image = null;
    try {
    image = ImageIO.read(new ByteArrayInputStream(data));
//  ImageIO.write(image, "JPEG", new File("C:/Users/Nicolas/Desktop")); // writing image to some specific folder.

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }



    return Response.ok(image).build();

}



public Connection connection(){
    Connection con = null;

    try {// set up driver for database
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


    try {
        con = DriverManager.getConnection("jdbc:mysql://aa1c9da17owdhky.cotr7twg0ekb.us-west-2.rds.amazonaws.com/test","nightskycode","uocb4t111");
    //  boolean reachable = con.isValid(10);// check for connection to DB


    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("No go!3");
    }
    return con;
  }

public Blob getPhoto(Connection con){

    Blob photo = null;
    Statement stmt = null;
    ResultSet rs = null;


    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery("Select photo from photos where photo_id = 7");

        if (stmt.execute("Select photo from photos where photo_id = 7")) {
            rs = stmt.getResultSet();

            while (rs.next()) { // results here
           photo =  rs.getBlob("photo");
            System.out.println(rs.getString("photo")); }
        }

    } 
    catch (SQLException ex){
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    }
    return photo;

}

这是我将数据上传到数据库的方式

@Path("/submitinfo" )
public class SubmitName {   

@POST
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(@FormDataParam("file") InputStream uploadedInputStream, @FormParam("first") String name) {
    Connection con = connection();

    postName(con, name);
    postPhoto(con, uploadedInputStream);
    return name; 


}


public void postPhoto(Connection con, InputStream uploadedInputStream){


    Statement stmt = null;
    String updateQuery = "INSERT INTO photos (photo) values ('" + uploadedInputStream + "')" ;
    System.out.println(updateQuery);

    try {
        stmt = con.createStatement();
        stmt.executeUpdate(updateQuery);
        con.close(); // Close the connection

    } catch (SQLException e) {
        e.printStackTrace();

    }

}

最佳答案

问题在于您如何尝试将数据存储为 blob。您需要使用 PreparedStatement - 具体来说,它的 setBlob()方法:

String mySQL = "INSERT INTO photos (photo) values (?)";
PreparedStatement pStmt = con.prepareStatement(mySQL);
pStmt.setBlob(1, uploadedInputStream);
pStmt.execute();

编辑以添加:它现在不起作用的原因是因为您连接了一个 String 来创建您的 SQL,并且您得到的结果是 InputStream.toString(),这是您看到的存储内容 - 它是默认的 Object.toString(),它是类名和哈希码的组合。

实际上,您应该始终使用PreparedStatement。它不仅使代码更清晰,而且为您处理引用/转义,这不太容易出错。

关于java - ImageIO.read 在字节数组上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736688/

相关文章:

sql-server - SSIS 中的 OData 目标

java - Jersey/MOXy 的 JSON 反序列化失败(HTTP 400)

java - 注入(inject)实例上的 Guice 空指针异常

java - 使用 JAX-RS/Jersey 访问数据库和共享资源?

java - ListView 没有在 fragment 中更新

java - Android - 在 Android 中设置自定义工具栏时出现 NullPointerException

php - 如何将mysql行存储到私有(private)数组变量中?

c# - Web 服务 session 在调试时有效,但在发布时无效

java - 在 Java 中为控制台格式化文本输出

java - 应用程序服务器在 OOM 异常时重启