Returning File as response to REST Request

8 Feb 2016
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. 

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.

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)


+ Recent posts