Sunday 19 June 2011

How to programmatically download attachments from list items

To download an attachment, you must first find the download link and then redirect to another page.

The ending of the response from current page does not affect the functionalities on the second one.


using (SPSite site = new SPSite("http://SiteCollectionURL"))
{
using (SPWeb web = site.OpenWeb())
{
string file = string.Empty;
SPList list = web.Lists["MyList"];
SPListItem currentItem = myList.GetItemById(id);
if (currentItem["AttachmentName"] != null)
{
file = "/Lists/ MyList/Attachments/" +
id.ToString() + "/" +
currentItem["AttachmentName"].ToString();
System.Web.HttpContext.Current.Session["FileName"] =
currentItem["AttachmentName"].ToString();
System.Web.HttpContext.Current.Session["Attachment"] =
file.Trim();
}
else
{
lblReport.Text = "No File name found";
}
if (file != string.Empty)
{
Reponse.Redirect("download.aspx");
}
}
}

On the download.aspx page, you need to the code shown below to download the file.

if (System.Web.HttpContext.Current.Session["Attachment"] != null)
{
string strName = System.Web.HttpContext.Current.Session["FileName"].ToString();
string sbURL = System.Web.HttpContext.Current.Session["Attachment"].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding =
System.Text.Encoding.Default;
response.AppendHeader("Content-disposition", "attachment; filename=" + strName);
response.AppendHeader("Pragma", "cache");
response.AppendHeader("Cache-control", "private");
response.Redirect(sbURL);
response.End();
}

No comments:

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...