I am trying to save a file (image, word, pdf or any type) in a database via a FileUpload control in asp.net (i.e. file.Docx etc). I then wish to display the file name as a link in a GridView so when the user clicks it, the file will be downloaded.
I have tried everything. In debugging it shows nothing. It reaches the end of Response.End but downloads nothing.
GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnLinkDownloadTender" runat="server" Text='<%# Eval("UploadedTenderPath") %>'CommandArgument='<%# Eval("UploadedTenderPath") %>' OnClick="DownloadTender"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Upload:
protected void UploadTender()
{
try
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadedTenders/") + fileName);
HdnFieldUploadedTender.Value = fileName;
ResultLabel.ResultLabelAttributes("Tender Uploaded", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
else
{
ResultLabel.ResultLabelAttributes("No file specified", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
}
}
Download:
protected void DownloadTender(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath) );
Response.Write(filePath);
Response.End();
}
Folder structure:
Try the following, also give us more information about your page. also if you are using chrome check that chrome isn't blocking it
var fileInfo = new FileInfo(filePath);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(File.ReadAllBytes(fileInfo.FullName));
Response.Flush();
Response.End();
Edit: In your gridview Row Databound add the following
LinkButton lb = e.Row.FindControl("btnLinkDownloadTender") as LinkButton;
if (lb != null)
ScriptManager.GetCurrent(this).RegisterPostBackControl(lb);
The above code will register the LinkButton to cause a Full Postback, this will allow the Download to succeed, the same will apply when doing an upload of a file in an Update Panel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With