Exploring File Upload and Download in MVC 3

by Hozefa 10. August 2012 17:04

For the file upload control on the View, the post action will return a HttpPostedFileBase class object to the Controller. HttpPostedFileBase serves as the base class for classes that provide access to individual files that have been uploaded by a client.

The view for File upload and Submit button on it will be as below:

@using (Html.BeginForm("OpenFile", "Home", FormMethod.Post, 
             new {enctype="multipart/form-data"})) 
{
    <input id="fileControl" type="file" name="Document" />
    <br />
    <input type="submit" value="Open File" />
}

Note:

new {enctype="multipart/form-data"}

is added because when you make a POST request, you have to encode the data that forms the body of the request in some way. HTML forms provide two methods of encoding. The default is application/x-www-form-urlencoded, which is more or less the same as a query string on the end of the URL. multipart/form-data is a more complicated encoding but one which allows entire files to be included in the data. Are far as the client is concerned: Use multipart/form-data when you have an <input type="file">

Now the Home controller action OpenFile will be like,

public FileContentResult OpenFile(HttpPostedFileBase Document)
{
    byte[] data = null; 

    if (Document != null)
    {
        using (Stream inputStream = Document.InputStream)
        {
            MemoryStream memoryStream = inputStream as MemoryStream;
            if (memoryStream == null)
            {
                memoryStream = new MemoryStream();
                inputStream.CopyTo(memoryStream);
            }
            data = memoryStream.ToArray();
        }
    }
    
    return File(data, Document.ContentType, "SampleDoc.pdf");
}

 Default Content-Disposition is attachment in IE. This will prompt for the Save dialog but inorder to open the file on the browser, add Content-Disposition as inline to the Response object before return File()...

Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");

 Find the complete working solution at - FileUploadDemo.zip

Tags:

.NET | MVC3

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List