1

We are storing file as BLOB in mysql with its filename also.While uploading its working fine. Now we want to download it fron gridview this also works perfect. But the problem is that after downloading the fine when we try to open it it shows file format error. We are only dealing with office document and pdf only.

try
{
  int did = Convert.ToInt32(e.CommandArgument);
  DataSet path = download.GetresourcePath(did);
  byte[] fileFromDatabase = null;
  DataRow row = path.Tables[0].Rows[0];
  fileFromDatabase = (byte[])row["UPLFILE"];
  string filename = (string)row["FILENAME"];

  if (fileFromDatabase.Length > 0)
  {
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = string.Format("application/{0}",
      Path.GetExtension(filename).Substring(1));
    Response.AddHeader("content-disposition", 
      string.Format("attachment;filename={0}", filename));
    Response.BinaryWrite(fileFromDatabase);
    Response.Flush();
    Response.End();
  }
}
catch (Exception)
{
  return;
}
  1. Here did is the ID of the file we getting it from the grid view.
  2. filename is the name of the file we are getting from the database.
  3. fileFromDatabase is the BLOB file from Mysql and we converted it into Byte.

So can any one suggest me what i am doing wrong?

2 Answers 2

1

Try to remove the headers entries and add it manually.

 Response.Clear();
 Response.ClearHeaders();
 Response.AddHeader("Content-Type", "application/octet-stream");
 Response.AddHeader("Content-Length", fileFromDatabase.Length.ToString());
 Response.AddHeader("Content-Disposition",string.Format("attachment;filename={0}", filename));
 Response.BinaryWrite(fileFromDatabase);
 Response.Flush();
 Response.End();
Sign up to request clarification or add additional context in comments.

3 Comments

sorry it giving same error while opening the file after it has been download.
@Aaraadhana - May be the content of file is saved incorrectly. Try to save the content of BLOB field into disk file and open it.
The file got corrupted.Thanks
0

I suggest that you don't store files as BLOBs. It is very bad for performance, if nothing else.

You should store the files in the server's filesystem, and in the database store the path to the file.

1 Comment

The file size will be maximum 4MB. Any way can you tell me why its showing file format error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.