Click here to Skip to main content
15,880,891 members
Articles / Web Development / ASP.NET
Tip/Trick

Returning File as response to REST Request

Rate me:
Please Sign up or sign in to vote.
3.56/5 (8 votes)
8 Feb 2016CPOL2 min read 74.7K   10   4
Returning File as response to REST Request

Introduction

This article demonstrates how to get a file as response to a REST request. I have posted my workng solution here for reference. This would help general user to write the code to implement this functionality.

Background

I was assigned a project to create a Web API which is used by SharePoint Link-To-Document, to return a file from a network drive which is different from the SharePoint Server machine. The user's requirement was that the file should be returned to user which he/she click on L-To-D  on a SharePoint site. As I struggled to find a working code the purpose, so, I decided to share my sample code for the reference of other developers.

Using the code

Here we see the step by step approach to create a Web API service which return files as response. During this demo project I will be using Visual Studio (VS) 2012 as IDE.

Step 1: In VS IDE, click on Add New Project. Select Web from Templates and then select Visual Studio 2012 under Web. Select ASP.Net MVC 4 Web Application from types of application (as shown below). Give Name of the solution as ReturnFile and click on OK. 

Image 1

Step 2: Once you click on OK you will be prompted will another pop-up. In the second pop-up select template as Web API and click on OK. VS will take a moment to create a solution for you and your FileService solution will be ready.

Image 2

Image 3

Step 3: Right Click on controller folder and select Add -> Controller. Give Name of the controller as FileController, and click OK. FileController.cs will be added to your Controllers folder.

Step 4: Open FileController.cs and and delete the default methods inside class FileController.cs. Now add a method GetFile, which will called from the REST request.

public HttpResponseMessage GetFile(string networkPath, string siteCollection, string library, 
          string folder, string fileName, string fileExtension)
{
     string filePath = string.Format(@"{0}\{1}\{2}\{3}\{4}.{5}", networkPath, siteCollection, library, 
                           folder, fileName, fileExtension);
     string file = string.Format("{0}.{1}", fileName, fileExtension);

     return DownloadFile(filePath, file);
}

The above method acts as a wrapper, formats the strings and calls another method which do processing as returns file stream in Message Response.

Step 5: Create method DownloadFile to search, process and return file in HttpMessageResponse.

private HttpResponseMessage DownloadFile(string downloadFilePath, string fileName)
{
    try
    {
          //Check if the file exists. If the file doesn't exist, throw a file not found exception
          if (!System.IO.File.Exists(downloadFilePath))
          {
                throw new HttpResponseException(HttpStatusCode.NotFound);
          }

          //Copy the source file stream to MemoryStream and close the file stream
          MemoryStream responseStream = new MemoryStream();
          Stream fileStream = System.IO.File.Open(downloadFilePath, FileMode.Open);

          fileStream.CopyTo(responseStream);
          fileStream.Close();
          responseStream.Position = 0;

          HttpResponseMessage response = new HttpResponseMessage();
          response.StatusCode = HttpStatusCode.OK;

          //Write the memory stream to HttpResponseMessage content
          response.Content = new StreamContent(responseStream);
          string contentDisposition = string.Concat("attachment; filename=", fileName);
          response.Content.Headers.ContentDisposition = 
                        ContentDispositionHeaderValue.Parse(contentDisposition);
          return response;
      }
      catch
      {
          throw new HttpResponseException(HttpStatusCode.InternalServerError);
      }
}

Points of Interest

The code above work for the file type like pdf, doc, mov, mp3, PNG, TIF, JPEG, etc. We don't need to write a separate logic based on filetype.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHave you consider to post this as a tip? Pin
Nelek19-Jan-16 5:49
protectorNelek19-Jan-16 5:49 
QuestionThe return is not really a stream. Pin
Paulo Zemek4-Jan-16 11:13
mvaPaulo Zemek4-Jan-16 11:13 
AnswerRe: The return is not really a stream. Pin
Rohit Kejriwal4-Jan-16 17:44
professionalRohit Kejriwal4-Jan-16 17:44 
QuestionUm Pin
Sacha Barber4-Jan-16 7:22
Sacha Barber4-Jan-16 7:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.