Image uploading and Retrieval from DB2

2019-06-13 13:57发布

问题:

H! I'm trying to upload an image in a DB2 database. The image size is a JPG (6.76 kb - 6924 bytes).

The database table has a BLOB field of length 1048576.

My code to insert the image is as follows:

If fileup.PostedFile IsNot Nothing AndAlso fileup.PostedFile.FileName <> "" Then
   Dim imagesize As Byte() = New Byte(fileup.PostedFile.ContentLength - 1) {}
   Dim uploadedimage1 As HttpPostedFile = fileup.PostedFile

   uploadedimage1.InputStream.Read(imagesize, 0, CInt(fileup.PostedFile.ContentLength))

   Dim uploadedimage2 As New OleDbParameter("@Image", OleDbType.VarBinary, imagesize.Length)
   uploadedimage2.Value = imagesize

   Dim cmd As New OleDbCommand()
   cmd.CommandText = "INSERT INTO xxx_TBL(x, IMAGE)  VALUES (?, ?)"
   cmd.Parameters.Add(x)
   cmd.Parameters.Add(uploadedimage2)

   cmd.Connection = clsDatabase.Open_DB()
   Dim result As Integer = cmd.ExecuteNonQuery()
   If result > 0 Then
      Return True

The image gets inserted into the Database.

The code to get the image from the Database, into a DataTable, which is then bound to a GridView to display on the webpage is as follows:

Dim cmd As New OleDbCommand()

cmd.CommandText = "SELECT x, IMAGE FROM xxx_TBL WHERE y = 1" 

cmd.Connection = clsDatabase.Open_DB()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)

Dim dt As New DataTable
dt.Columns.Add(New DataColumn("Comments", GetType(String)))
dt.Columns.Add(New DataColumn("Picture", GetType(Bitmap)))

Do While (dReader.Read())
   Dim dr As DataRow = dt.NewRow()

   dr("Comments") = dReader(0).ToString
   Dim imageobj = dReader(1)
       Using ms As New System.IO.MemoryStream
            Dim bm As Bitmap
            Dim bytearray = DirectCast(imageobj, Byte())
            ms.Write(bytearray, 0, bytearray.length)
            bm = New Bitmap(ms)
            dr("Picture") = bm
       End Using

    dt.Rows.Add(dr)
Loop

GridView1.DataSource = dt
GridView1.DataBind()

x comes from the Database fine, and is displayed. However, I get no picture - just a small "missing picture (red cross on white) icon".

On checking the database, the length of the image in BLOB field is 8192. However, on copying it onto a 'TEST' File (no extension), the size was 13848 bytes. I'm guessing that could be because of the way DB2 reads/encodes the image binary, but I'm not sure. Could someone please highlight the possible causes of error? Any suggestions on making this work or debugging?

回答1:

I'm not familiar with DB2 but since you are able to display comments, your image should be read properly. Let's assume your image data is also stored properly, your code will not display them in the browser because they need a little different care then comments. Each image needs to be an additional HTTP request to your server, so you'll have to create those <img src=myImg.png> tags in place of image holders.

In your dt, you don't need the actual image data, you just need the ID to the image because you'll need to use a HttpHandler to retrieve the image and then stream to browser.

first, you'll need a <img> tag in your GivdView1's image column.

then, during data binding, make sure to update it to <img src="MyHttpHandler.ashx?id=1"/>, of course, the ID value must be dynamic.

now, add a new file Generic Handler to your Visual Studio project and name it MyHttpHandler.ashx and code something like below:

public class MyHttpHandler : IHttpHandler
{    
    public void ProcessRequest(HttpContext context)
    {
        string sid = context.Request.QueryString["id"];
        int id = -1;
        if(int.TryParse(sid, out id) && id > 0){
            cmd.CommandText = "SELECT IMAGE FROM xxx_TBL WHERE ID=" + id.ToString() + ";";
            byte[] img = dr["IMAGE"];
            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(img);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Now, after gridview renders the html, the browser will make HTTP request for all those images and your MyHttpHandler.ashx will stream each image back for browser to display.