SharePoint: Download a file programatically

Hi All,

Downloading a file from SharePoint using the code is not a typical task. In .net we usually get the binary of the file and check the content type of the file based on extension and then write the binary to the HttpResponse of the page and bingooo!!!!

Its not that much complicated if you are a SharePoint coder. Thing is you just need to have the Url of the file.

As we all know that we can either code server side or client side, so you can choose one of the following solution as per your requirement:

From Code behind:

btnDownload.OnClientClick = “STSNavigate(‘” + SPContext.Current.Web.Url+ “/_layouts/15/download.aspx?SourceUrl=” + documentUrl + “‘ ); return false;”;

From Client side:

//Download file button click event
$(‘#<%=btnDownload.ClientID%>’).click(function (e) {

// Write logic to create the url in my case I was iterating through grid rows and chech which //check box is seleced and then get the Field ref of the item and create the url to download
STSNavigate(‘<%= SPContext.Current.Web.Url %>/_layouts/15/download.aspx?SourceUrl=’ + url);
return false;

Using “STSNavigate” method we can navigate to the download.aspx which already having stuff to run for downloading the file. The SourceURL should be the path of the file. It can be path from the document library item.

(Hint: we can create the Url of the file by concatinating “FieldRef and “EncodedAbsUrl” column values of the list Item).

One more important thing, its “return false;” this line will stop the your parent page to reload after downloading finishes.

Well hope my blog is helpful for you 🙂 Please comment if you find it useful.

Happy SharePointing 🙂