Returning File as response to REST Request

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.

No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...