Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I have written a code for my web application, i which i am uploading some files (Pdf and png etc) and displaying the files in the gridview. I am desirous to download the uploaded file from gridview on clicking the row. I have successfully done that task, but when i open the downloaded file, i face the error that "File is unable to open". How i can get rid from that.

Here is my code which i am using to download the file from the gridview.

What I have tried:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {

Response.Clear();
Response.ContentType = "application/octect-stream";
Response.AppendHeader("content-disposition","filename="+ e.CommandArgument);

Response.End();
}
}
Posted
Updated 23-Apr-17 21:28pm
Comments
Dave Kreskowiak 23-Apr-17 14:23pm    
Do you want to take a real close look at that code you posted? Where are you sending the content of the file back to the client? So far, you just created a header for the file you're sending back, not the file itself.
Hassaan_Malik 23-Apr-17 14:27pm    
I am beginner to asp.net. its my first interaction with that. Can you please slightly guide me regard that or can you please send me any useful link from where i can get help?. Any sort of help will be highly appreciated. Please
[no name] 23-Apr-17 14:31pm    
https://www.asp.net/web-forms/books

You aren't going to get your project done by guessing and asking question after question. You need to learn the correct way.

1 solution

you need to do like below code
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string contentType = FileUpload1.PostedFile.ContentType;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);

Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = contentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();


code is not tested you need to check
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900