Downloading a Sitefinity Document From the Database

by Stephen Horn Sep 16, 2014

dwnldListExampleSitefinity has had a nice Download List widget available to present documents that you would like to make available to users. You can add these lists on an open page, or you can put them on a page that is hidden, that perhaps requires the user to fill out a form before they are redirected to page. Nice.

 However, what if you want more control on how you serve or use your documents?  Perhaps you have a situation where you want to be able to retrieve the document into a file stream, but do not know how to get the document bytes out of the database and into that stream.  The solution is actually very simple, just ask the Library Manger to do so for you. See an example here!

Here is a simple MVC example of how to use this approach:

// Action Method Requires the desired document's id
public FileStreamResult Request(string docId)
   var docIdGuid = new Guid(docId);
   LibrariesManager librariesManager = LibrariesManager.GetManager();
   // still need the document for MimeType and name
   Document doc = librariesManager.GetDocument(docIdGuid); 
   Stream stream = librariesManager.Download(doc.Id);
   return File(
      stream, // the stream
      doc.MimeType,  // conent type
      string.Format("{0}{1}", doc.Title, doc.Extension) // filename

You can see an example of this in action on our Sitefinity Examples Page!

Note:  In Hybrid Mode, there can be issues using the stream from the database when in an MVC Controller, so we had to use a custom route in the Global.asax file.  You can read more about this solution here:

To see another example of downloading the document straight from the database, in a Web Forms manner, including how to get the Document Id from a document title, see Stefani's blog post at:

Happy Downloading!

Contact A Sitefinity Expert Today!