Friday, 30 May 2014

Uploading and returning files in ASP.NET MVC




Description:-

            In this example I explain that how to uploading and returning or downloading file in mvc4 or asp.net mvc. Or returning file from mvc ActionResult to mvc View Page.

I already explain that how to upload file or multiple file in mvc4 previously http://aspsolutionkirit.blogspot.in/2013/08/how-to-upload-multiple-file-in-mvc.html  so now we direct concerntrate only on how to returning file from ActionResult or action Method to mvc view page.



Returning files through action results

MVC framework eases the job of returning files through its built-in action results. We don't need to worry about adding any headers in the response the action results will take care.

FileResult

FileResult  is an abstract class derived from ActionResult class that delegates writing the file in the response to the subclasses. This class contains only a single abstract method called WriteFile that every subclass should have implement this method.
FileResult class generally return a file that you want means if you return pdf file then it will open the pdf file in AdobeReader automatically,if you return word file then it will automatically open it in MSWord document.
This class mainly does the job of adding Content-Type and Content-Disposition headers into the response.
when users click on the download link, the Download action method returns a FileResult:
here is a code
 public FileResult Download(string ImageName)
{
   
return File("<your path>" + ImageName, System.Net.Mime.MediaTypeNames.Application.Octet);
}

However, you can also return  a many types that you want depend on situation that what type you want to return like FileContentResult, FilePathResult, or  FileStreamResult are also used to return file same like FileResult class.
Here is a description of each class and when you have to use this class
FileContentResult : Use this type when you want to use a byte array to access the file. In this process, you must have to obtained the file as a byte array from a database call.
return new FileContentResult(byteArray, "image/jpeg");
FilePathResult  : Returns a file on disk when you must access via a file path. In the FilePathResult you can return a File type or a FileStreamResult.
return new FilePathResult("~/App_Data/Images/" + ImageName, System.Net.Mime.MediaTypeNames.Application.Octet);
FileStreamResult : Sends a stream out to the response.

return new FileStreamResult(new FileStream("<your path>", FileMode.Open), "image/jpeg");
This entry was posted in :

0 comments:

Post a Comment