Click here to Skip to main content
11,638,173 members (76,413 online)
Click here to Skip to main content

Tagged as

Uploading and returning files in ASP.NET MVC

, 15 Apr 2014 CPOL 170.4K 1 87
Rate this:
Please Sign up or sign in to vote.
Index 1. Brief 2. How to upload a file? 2.1 Basics 2.2. Reading files from request 3. HttpPostedFileBase 3.1. Behind the scenes 3.2. HttpPostedFileBaseModelBinder 3.3. HttpFileCollectionValueProvider 4. Uploading multiple files 5. Using view models to validate POSTed files 5.1. FileSizeAttribute




Uploading and sending files in an ASP.NET MVC application is very simple. The POSTed file(s) are available as parameters directly in actions through model binding. The files in the server can be easily sent as response to the clients through its rich support of action results.

There are already articles written on this subject. So why another article? Well, in this article I gathered the important concepts that are scattered in different posts, threads in a single place. I'm sure this article will help the MVC programmers to increase their grip on the framework.

How to upload a file?


POSTing a file to the server is quite simple. All we need is a html form having encoding type set to multipart/form-data and a file input control.

<form action="/profile/upload"  method="post" enctype="multipart/form-data">

    <label for="photo">Photo:</label>
    <input type="file" name="photo" id="photo" />

    <input type="submit" value="Upload" />

Listing 1. Simple file upload html form

An important thing developers forget sometimes is setting the encoding type(enctype) to multipart/form-data. As default the encoding type is application/x-www-form-urlencoded which is insufficient for sending large amount data to server especially when the form contains files, non-ASCII data and binary data.

When you post the form the Content-Type header is set to multipart/form-data. When you forget setting the proper encoding type then only the filename is submitted not the file.

Reading files from request

The POSTed files are available as HttpFileCollectionBase in Request.Files. In the below listing we can see how to read the POSTed file from the request and save to the server.

public ActionResult Upload()
    string path = @"D:\Temp\";
    HttpPostedFileBase photo = Request.Files["photo"];
    if(photo != null)
        photo.SaveAs(path + photo.FileName);
    return RedirectToAction("Index");

Listing 2. Upload action

Instead of manually reading the file from the Request by taking the advantage of model binding the file can be made directly available as a parameter in the action as shown in the below listing.

public ActionResult Upload(HttpPostedFileBase photo)
    string path = @"D:\Temp\";
    if(photo != null)
        photo.SaveAs(path + photo.FileName);
    return RedirectToAction("Index");

Listing 3. Using HttpPostedFileBase as action parameter

The important thing to note down is the file parameter name should be same as the name of the file input control and in the above case it is photo.


HttpPostedFileBase is an abstract class that contains the same members as in HttpPostedFile. Prior to the .NET framework 3.5 version there was only HttpPostedFile which is concrete and sealed making the code hard to unit-test. The HttpPostedFileBase is created to substitute HttpPostedFile in MVC applications for better unit testing. So wherever you need to read files I advise you to use HttpPostedFileBase instead of HttpPostedFile.

An important thing to note down is we can't directly substitute HttpPostedFile with HttpPostedFileBase because HttpPostedFile is still the same, not derives from any type. In some cases we need to convert HttpPostedFileBase to HttpPostedFile and we can achieve that using the HttpPostedFileWrapper.

Behind the scenes

As many of us already aware it's the model binding feature that maps the POSTed file to HttpPostedFileBase in the action parameter. But what we are interested here is to know the supporting classes.

The model binding feature relies on two types of components binders and value providers. The value providers are the components that gets the value needed from the particular source (query-strings, form etc.) and feed to binders. The binders are the components that really fills the properties of a model or the parameters in the action with those values.

The MVC framework is designed in such a way that these two components are loosely coupled and hence a binder don't need to worry about which value provider it has to interact to get the value for a property or parameter likewise a value provider don't need to worry about who is asking the value.


When you have a single instance of HttpPostedFileBase as an action parameter or a property in model then mapping the file is completely done by the HttpPostedFileBaseModelBinder and no value providers are used in this case. You may think why no value providers are used in this case, it's because the source is single and clear i.e. Request.Files collection.


When model binding collection of POSTed files, the HttpFileCollectionValueProvider comes into play along with the DefaultModelBinder. The HttpFileCollectionValueProvider which derives from the DictionaryValueProvider stores all the POSTed files as a dictionary and feeds the DefaultModelBinder with files whenever it needs to map a parameter or property of type HttpPostedFileBase.

Uploading multiple files

So uploading a single file and reading it from the server is quite easy, all we need is to set the HttpPostedFileBase type as a parameter in the corresponding action method. How about reading multiple files POSTed to the server? We can easily achieve this by setting an IEnumerable<HttpPostedFileBase> as action parameter.

Here is a sample html form to upload multiple files.

<form action="documents/upload"  method="post" enctype="multipart/form-data">
    <label for="photo">Photo:</label>
    <input type="file" name="[0].files" id="files_0" />
    <input type="file" name="[1].files" id="files_1" />
    <input type="file" name="[2].files" id="files_2" />

    <input type="submit" value="Upload" />

Listing 4. Form to upload multiple files

Below is the action that handles the POST request of the form.

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    foreach(var file in files)
    return RedirectToAction("Index");

Listing 5. Using IEnumerable<HttpPostedFileBase> as action parameter to receive multiple POSTed files

The important thing is the name of the file input controls should match the rules of model binding.

Using view models to validate POSTed files

Like any other input data the POSTed files to the server also needs validation. For example, in the case of image we need the file should be one of the supported image types like jpg, jpeg, png by the server and we may also need validations to check the file size, file name etc. before persisting the file in the server.

When we use the HttpPostedFileBase directly as action parameter then we have to validate the file manually as shown in the below listing.

public ActionResult Upload(HttpPostedFileBase photo)
    if (photo != null)
        string path = @"D:\Temp\";
        if (photo.ContentLength > 10240)
            ModelState.AddModelError("photo", "The size of the file should not exceed 10 KB");
            return View();
        var supportedTypes = new[] { "jpg", "jpeg", "png" };
        var fileExt = System.IO.Path.GetExtension(photo.FileName).Substring(1);
        if (!supportedTypes.Contains(fileExt))
            ModelState.AddModelError("photo", "Invalid type. Only the following types (jpg, jpeg, png) are supported.");
            return View();
        photo.SaveAs(path + photo.FileName);
    return RedirectToAction("Index");

Listing 6. Uploading file with validations

In the above action we have done couple of validations against the uploaded file. Instead of doing it manually it would be great if you could do that using data annotation attributes and for that we have to use view models.

Lets create a view model that wraps HttpPostedFileBase as a property which is decorated with data annotation attributes.

public class UploadFileModel
    public HttpPostedFileBase File { get; set; }

Listing 7. View model

Note that the validation attributes applied over the File property are custom ones and not exists in the data annotations assembly.

Creating custom validation attribute is not a difficult job! All we have to do is derive a class from ValidationAttribute and override the IsValid and FormatErrorMessage methods. Here are our implementations for FileSizeAttribute and FileTypesAttribute.


public class FileSizeAttribute : ValidationAttribute
    private readonly int _maxSize;

    public FileSizeAttribute(int maxSize)
        _maxSize = maxSize;

    public override bool IsValid(object value)
        if (value == null) return true;

        return _maxSize > (value as HttpPostedFile).ContentLength;

    public override string FormatErrorMessage(string name)
        return string.Format("The file size should not exceed {0}", _maxSize);

Listing 8. FileSizeAttribute


public class FileTypesAttribute: ValidationAttribute
    private readonly List<string> _types;

    public FileTypesAttribute(string types)
        _types = types.Split(',').ToList();

    public override bool IsValid(object value)
        if (value == null) return true;

        var fileExt = System.IO.Path.GetExtension((value as HttpPostedFile).FileName).Substring(1);
        return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);

    public override string FormatErrorMessage(string name)
        return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types));

Listing 9. FileTypesAttribute

Finally we have to replace the action parameter from HttpPostedFileBase to UploadFileModel and the validations will happen automatically when the binding happens. The below listing shows the simplified version of the upload action after using view model.

public ActionResult Upload(UploadFileModel fileModel)
    string path = @"D:\Temp\";
        if(fileModel != null && fileModel.File != null)
            photo.SaveAs(path + fileModel.File.FileName);
        return RedirectToAction("Index");
    return View();

Listing 10. Upload action with view model for validations

So far we have seen how to upload files to server and validate them using data annotations. In the coming sections we will see how we can easily return a file as response to the clients.

How to return a file as response?

How a browser knows what file type is returned from the server?

The Content-Type header is the one that says the browser what kind of file is being returned from the server. For example, to return a pdf file from the server the Content-Type should be set to application/pdf. Likewise to return a png image, the Content-Type should be image/png and so on.

For some content types the browser doesn't open the save dialog and display the content directly inside its window. Example, when you return a pdf file, some browsers knows how to display the pdf files inside it, same for images. For the content-types the browser can't display to the user it opens the save dialog ex. when you return an excel report from the server.

When the user want to save the file sent to the browser, the server can suggest a filename to the client and the Content-Disposition header is just for that.

To return a file from server all we have to do is set the proper Content-Type, Content-Disposition headers and write the file into the response. The below code snippet shows how we can return a file just plain from an action without using action results.

public void GetReport()
    Response.ContentType = "application/text";
    Response.AddHeader("Content-Disposition", @"filename=""IT Report.xls""");

Listing 11. Sending an excel report from server

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.


This is an abstract class derived from ActionResult that delegates writing the file in the response to the subclasses. This class contains a single abstract method called WriteFile that every subclass should implement.

This class mainly does the job of adding Content-Type and Content-Disposition headers into the response. Adding the Content-Type header is not a big deal while determining the value of the Content-Disposition header is not an easy job and the FileResult class uses a private class ContentDispositionUtil for that purpose.

The ContentDispositionUtil tries first to get the header value using the ContentDisposition class which is located in the System.Net.Mime namespace. If it fails then generate the header value based on RFC 2231 from its own methods. To understand how it generates the header see the source code.

There are three built-in classes that implements FileResult: FilePathResult, FileContentResult and FileStreamResult.

File action results class diagram


This action result is used to return a file from the server's physical location.

public FileResult InsuranceReport()
    string fileName = @"c:\docs\insurance_report.pdf";
    string contentType = "application/pdf";

    return new FilePathResult(fileName, contentType);

Listing 12. Returning file from path

We can even pass a file download name to the FilePathResult,

return new FilePathResult(fileName, contentType)
    FileDownloadName = "InsuranceReport.pdf" 

Listing 13. Passing file download name

Internally the FilePathResult class calls the TransmitFile method of HttpResponseBase to send the file in response. You can see the complete code of FilePathResult here.


This class is used to return a file from a byte array.

return new FileContentResult(byteArray, "application/pdf");

Listing 14. Returning file from byte array

The FileContentResult writes the complete byte array to the response's OutputStream at-once. You can see the complete code of FileContentResult here.


This action result is used to return a file from a stream.

return new FileStreamResult(fileStream, "application/pdf");

Listing 15. Returning file from stream

The FileStreamResult reads chunks of data from the stream and write into the response. The size of each chunk is 4KB and this can't be changed through code or config. You can see the source code here.

Controller helper methods to return files

Actually you don't need to instantiate the FileResult types from action methods the Controller has bunch of built-in methods that helps to easily send a file in response.

The following are the helper methods available in controller.

Helper method Returning type
File(byte[] fileContents, string contentType) FileContentResult
File(byte[] fileContents, string contentType, string fileDownloadName) FileContentResult
File(Stream fileStream, string contentType) FileStreamResult
File(Stream fileStream, string contentType, string fileDownloadName) FileStreamResult
File(string fileName, string contentType) FilePathResult
File(string fileName, string contentType, string fileDownloadName) FilePathResult

You can rewrite the code shown in Listing 12. using the helper method as below,

public FileResult InsuranceReport()
    return File(@"c:\docs\insurance_report.pdf", "application/pdf");

Listing 16. Returning file using the helper method

Creating custom file action result

We can easily create new file action results by deriving from the the abstract class FileResult. For example, let see how we can create a custom action result that return files from string, let's call it FileStringResult.

public class FileStringResult : FileResult
    public string Data { get; set; }

    public FileStringResult(string data, string contentType)
        : base(contentType)
        Data = data;

    protected override void WriteFile(HttpResponseBase response)
        if (Data == null) { return; }

Listing 17. Creating a custom file action result

We can use our FileStringResult as shown in the below action.

public FileResult FinanceReport()
    string reportString = ...
    return new FileStringResult(reportString, "application/text"){ FileDownloadName = "finance-report.csv" };

Listing 18. Returning file from string.


In this article we learnt many things about uploading and returning files in an MVC application. We saw how we can apply validations to the POSTed files easily using view models. We discussed about the different types of file action results that helps to return files from the server and even we created a custom file action result.


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


About the Author

Software Developer Trigent Software Private Limited
India India
I'm a software developer from south tip of India. I spent most of the time in learning new technologies. I've a keen interest in client-side technologies especially JavaScript and admire it is the most beautiful language ever seen.

I like sharing my knowledge and written some non-popular articles. I believe in quality and standards but blames myself for lagging them.

I believe in small things and they makes me happy!

You may also be interested in...

Comments and Discussions

GeneralOne of best article ever read! Pin
Member 1124465210-Feb-15 0:31
memberMember 1124465210-Feb-15 0:31 
BugImages are broken Pin
tyaramis2-Feb-15 4:24
membertyaramis2-Feb-15 4:24 
GeneralMy vote of 5 Pin
Gaurav.Kumar.Arora27-Oct-14 10:50
memberGaurav.Kumar.Arora27-Oct-14 10:50 
Generalmultiple-file-upload-with-aspnet-mvc Pin
Binu198513-Jun-14 1:24
memberBinu198513-Jun-14 1:24 
QuestionNice. A question! Pin
M.Khadem16-Mar-14 22:29
memberM.Khadem16-Mar-14 22:29 
AnswerRe: Nice. A question! Pin
After205014-Apr-14 20:46
memberAfter205014-Apr-14 20:46 
AnswerRe: Nice. A question! Pin
destar7721-Aug-14 0:14
memberdestar7721-Aug-14 0:14 
Questionhave a problem when using view Model Pin
Ho0otan17-Feb-14 11:52
memberHo0otan17-Feb-14 11:52 
QuestionReally good article Pin
Samer Abu Rabie16-Feb-14 16:35
memberSamer Abu Rabie16-Feb-14 16:35 
GeneralThanks Pin
Thiago N. Oliveira21-Jan-14 2:16
memberThiago N. Oliveira21-Jan-14 2:16 
QuestionUpload and Display image without post Pin
chuki216-Oct-13 22:37
memberchuki216-Oct-13 22:37 
AnswerRe: Upload and Display image without post Pin
Member 1058647213-Feb-14 19:15
memberMember 1058647213-Feb-14 19:15 
GeneralMy vote of 5 Pin
Power Programer21-Aug-13 1:23
memberPower Programer21-Aug-13 1:23 
SuggestionOnly (tiny thing) you might wish to add Pin
Mcshaz7-Jun-13 14:52
memberMcshaz7-Jun-13 14:52 
GeneralMy vote of 5 Pin
Debasis Goswami10-May-13 4:59
memberDebasis Goswami10-May-13 4:59 
Question5 Pin
mikeperetz1-Apr-13 3:46
membermikeperetz1-Apr-13 3:46 
QuestionAbout the HttpPostedFile in FileSizeAttribute and FileTypesAttribute Pin
Paul Ho26-Mar-13 18:39
memberPaul Ho26-Mar-13 18:39 
AnswerRe: About the HttpPostedFile in FileSizeAttribute and FileTypesAttribute Pin
Member 1058647213-Feb-14 19:13
memberMember 1058647213-Feb-14 19:13 
GeneralMy vote of 5 Pin
erdalkiran27-Feb-13 21:53
membererdalkiran27-Feb-13 21:53 
QuestionSingle file upload work as mentioned but multiple file upload not working Pin
gopal venkat14-Feb-13 4:34
membergopal venkat14-Feb-13 4:34 
AnswerRe: Single file upload work as mentioned but multiple file upload not working Pin
Dharmendra Kashyap24-Dec-13 8:33
memberDharmendra Kashyap24-Dec-13 8:33 
GeneralMy vote of 5 Pin
techtalk74-Feb-13 11:55
membertechtalk74-Feb-13 11:55 
GeneralMy vote of 5 Pin
Member 11135751-Feb-13 4:26
memberMember 11135751-Feb-13 4:26 
GeneralMy vote of 5 Pin
Ankhara22-Jan-13 17:53
memberAnkhara22-Jan-13 17:53 
GeneralMy vote of 5 Pin
felipe.miosso22-Dec-12 5:50
memberfelipe.miosso22-Dec-12 5:50 
GeneralMy vote of 1 Pin
Rachel Fishman19-Sep-12 3:27
memberRachel Fishman19-Sep-12 3:27 
GeneralRe: My vote of 1 Pin
After205019-Sep-12 22:42
memberAfter205019-Sep-12 22:42 
GeneralRe: My vote of 1 Pin
Debasis Goswami10-May-13 5:01
memberDebasis Goswami10-May-13 5:01 
GeneralMy vote of 5 Pin
ghprogrammingco2-Sep-12 23:45
memberghprogrammingco2-Sep-12 23:45 
GeneralRe: My vote of 5 Pin
After20503-Sep-12 4:36
memberAfter20503-Sep-12 4:36 
GeneralMy vote of 5 Pin
Christian Amado29-Aug-12 11:02
memberChristian Amado29-Aug-12 11:02 
GeneralRe: My vote of 5 Pin
After205031-Aug-12 2:30
memberAfter205031-Aug-12 2:30 
GeneralMy vote of 5 Pin
Nitesh Maharaj29-Aug-12 3:51
memberNitesh Maharaj29-Aug-12 3:51 
GeneralRe: My vote of 5 Pin
After205029-Aug-12 6:58
memberAfter205029-Aug-12 6:58 
GeneralMy vote of 5 Pin
SleepyCrat21-Aug-12 2:45
memberSleepyCrat21-Aug-12 2:45 
GeneralRe: My vote of 5 Pin
After205021-Aug-12 3:47
memberAfter205021-Aug-12 3:47 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150728.1 | Last Updated 15 Apr 2014
Article Copyright 2012 by After2050
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid