display image from Mysql database without storing

2019-09-02 07:53发布

问题:

I'm developing a Struts application where I want to display images present in MySQL DB in BLOB datatype.

I don't want to store those images to local system but I want to directly display them in a browser. We need to store them in an temp memory. I am able to fetch it and store it into FileOutputStrem and from this object i need to pass an image to JSP.

Below is the code

ResultSet result = statement.executeQuery();

if (result.next()) {
    Blob blob = result.getBlob("photo");
    InputStream inputStream = blob.getBinaryStream();
    // read the input stream...

}

Please let me know how can I do this.

回答1:

You can use

byte[] content = result.getBytes("photo");
response.setContentType("image/jpg");
response.setContentLength(content.length);
response.getOutputStream().write(content);

Html Code

$(document).ready(function () {
    $("#submit").click(function () {
        $.ajax({
            type: "GET",
            url: "servleturl",
            success: function (result) {
                $("#content").html('<img src="'+result+'" >'); 
            }
        });
    });
});