Downloading File using stream on sharepoint page

Description

This article will show you how to buffer data into a MemoryStream from a query and output the buffered data back to the browser as a dialog (with save open cancel).

The Code:

– The first step is to get object of SPSite and SPWeb.
– Second steps is to get SPListItem object using file path.
– Third step is to get bytes and put in Response object.

The following function give shows how this can be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/// <summary>
/// It get bytes from source document which exist on sharepoint document library
/// give a popup for download
/// </summary>
/// <param name="filePath">Full path of file</param>
/// <param name="Response">Page Response object</param>
public static void download(string filePath, HttpResponse Response, Uri siteUri)
{
	using (SPSite site = new SPSite(siteUri.ToString()))
	{
		using (SPWeb web = site.OpenWeb())
		{
			SPListItem item = web.GetListItem(filePath);
			string fileName = System.IO.Path.GetFileName(filePath);
			// set the http content type to "APPLICATION/OCTET-STREAM 
			Response.ContentType = "APPLICATION/OCTET-STREAM";
			// initialize the http content-disposition header to 
			// indicate a file attachment with the default filename
			System.String disHeader = "Attachment;Filename="" + fileName + """;
			Response.AppendHeader("Content-Disposition", disHeader);
 
			byte[] buffer = item.File.OpenBinary();
			int length = buffer.Length;
			Response.OutputStream.Write(buffer, 0, length);
 
			Response.Flush();
			Response.Close();
		}
	}
}

Summary

As you can see this solution is pretty straight forward. Through the use of a memorystream and header manipulation you are able to dynamically retrieve data from a sharepoint content database and send it to the browser as a file.

Hope it helps!!
Thanks.

calendarFebruary 24, 2012 · cardInfoyen · commentsNo Comments
tagTags: , , , , ,  · Posted in: ASP .NET, MOSS, SharePoint, SharePoint 2010

Leave a Reply

Spam Protection: , required

myworldmaps infoyen