Click here to Skip to main content
13,793,550 members
Click here to Skip to main content
Add your own
alternative version

Stats

32.3K views
10 bookmarked
Posted 8 Feb 2016
Licenced CPOL

Returning File as response to REST Request

, 8 Feb 2016
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Rohit Kejriwal
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionHave you consider to post this as a tip? Pin
Nelek19-Jan-16 6:49
protectorNelek19-Jan-16 6:49 
QuestionThe return is not really a stream. Pin
Paulo Zemek4-Jan-16 12:13
professionalPaulo Zemek4-Jan-16 12:13 
AnswerRe: The return is not really a stream. Pin
Rohit Kejriwal4-Jan-16 18:44
professionalRohit Kejriwal4-Jan-16 18:44 
QuestionUm Pin
Sacha Barber4-Jan-16 8:22
mvpSacha Barber4-Jan-16 8: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.181207.3 | Last Updated 8 Feb 2016
Article Copyright 2016 by Rohit Kejriwal
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid