I have developed a custom web part to display all the items in a certain document library following the next link:
I've bound the "Link button"s in each repeater item to do the following:
protected void lbtn_download_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
RepeaterItem ritem = (RepeaterItem)btn.Parent;
string fileAbsUrl = ((HiddenField)ritem.FindControl("hf_fileName")).Value;
InvokeDownload(fileAbsUrl);
}
as shown above, I get the absolute file name from a hidden field in my RepeaterItem and then call the InvokeDownload method which follows the instructions provided in the link above.
Here's the code for the InvokeDownload method:
void InvokeDownload(string fileName)
{
string ext = fileName.Split('.')[fileName.Split('.').Length - 1];
string name = fileName.Split('/')[fileName.Split('/').Length - 1];
string contentType = "";
using (SPWeb web = SPContext.Current.Site.OpenWeb(SPContext.Current.Site.RootWeb.ID))
{
SPFile tempFile = web.GetFile(fileName);
string relativePath = tempFile.ServerRelativeUrl;
byte[] obj = (byte[])tempFile.OpenBinary();
switch (ext)
{
case "htm":
case "html":
contentType = "text/HTML";
break;
case "doc":
case "docx":
case "rtf":
contentType = "Application/msword";
break;
case "xls":
case "xlsx":
contentType = "Application/x-msexcel";
break;
case "pdf":
contentType = "application/pdf";
break;
default:
contentType = "text/plain";
break;
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
//Response.TransmitFile(Server.MapPath(fileName));
//Response.End();
if (Response.IsClientConnected)
{
Response.BinaryWrite(obj);
}
Response.Flush();
Response.Close();
}
}
When I click on the "download" linkButton it prompts me with the save file dialog which is OK so far but when I cancel that dialog and try to click on another item's download button nothing happens at all and no download is ever invoked..
Please, can anyone help?
Many thanks in advance.