Kiwimoisi
Kiwimoisi

Reputation: 4182

Retrieve BLOB file

I upload BLOB files in my SQL database. I create Dynamic Hyperlink redirecting to my downloading.aspx.cs , to download the files .

When I click on it , the only thing I retrieve is something like that :

*����JFIF,,��ExifMM*�   ���(1�2;%+>P?`���7��i��%��NIKON CORPORATIONNIKON D3-��'-��'Adobe Photoshop CS4 Macintosh2010:11:19 21:53:25 9�I�@d!ddGddd+�K�r� (��Ƃ�Έ"�'@�0221�֐����� ���� � ��,��42��42��42�0100����Р�d����J����R�b����   � ��Z @( 2010:11:19 20:44:392010:11:19 20:44:39 � ASCII  R030100��(�HH����JFIFHH��Adobe_CM��Adobed����* 

This is my Page_Load code in this downloading.aspx :

protected void Page_Load(object sender, EventArgs e)
{
    string filename = Request["file"].ToString();
    var conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"];
    string strConnString = conString.ConnectionString;
    SqlConnection dbConnection = new SqlConnection(strConnString);
    dynamic queryString = ("SELECT Data FROM Files WHERE Name = '" + filename + "'");
    SqlCommand theCommand = new SqlCommand(queryString, dbConnection);
    dbConnection.Open();
    SqlDataReader reader = theCommand.ExecuteReader();

    if (reader.Read() && reader != null)
    {
        Byte[] bytes;
        bytes = Encoding.UTF8.GetBytes(String.Empty);
        bytes = (Byte[])reader["Data"];
        Response.BinaryWrite(bytes);

        reader.Close();
    }

    dbConnection.Close();
}

Can someone tell me why? Thank you.

Upvotes: 1

Views: 1964

Answers (2)

Icarus
Icarus

Reputation: 63966

You need to set content type, and add content disposition to your response headers as so:

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
 Response.AddHeader("content-disposition", "attachment;  filename=whatever.xlsx");
 Response.BinaryWrite(yourbytes);

Note: content-type has to be specific to the type of file you are streaming. If an image, it has to be something like "image/jpg"; etc. Similarly for the header; if it's an image, probably you want to set the extension on the filename part to be "file.jpg". Above code is just an example

Upvotes: 5

Hikaru-Shindo
Hikaru-Shindo

Reputation: 1901

You need to send Content-Type, Content-Length and Content-Disposition headers to the browser so it can understand the binary data.

Upvotes: 3

Related Questions