Wednesday, May 19, 2010

Downloading an attachment from a SharePoint list

This post explains how to download a file which was uploaded as an attachment in a list.

Points to be noted
  • SPListItem has a propery "Attachments" which returns the list of file names as string. Remember this is not a physical file that is returned, just name of the file.
  • If we need to open up "Save As" dialog as opposed to displaying the file right on the browser, we need to write the file contents back to the Response object.

foreach (string fileName in _listItem.Attachments)
SPFile _file = _web.GetFile(_listItem.Attachments.UrlPrefix + fileName);
byte[] binFile = _file.OpenBinary();
base.Page.Response.ContentType = "image/jpeg";
base.Page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);

The above opens up the dialog box asking user if the file needs to be opened or saved.

Technorati Tags: ,,,

No comments:

Post a Comment