How to upload a file in an ASP.Net MVC page

For this example, I’m using a controller named “HomeController”, with the view “Index”. When you click the “Submit” button on the view, it will be submitted to the “Save” method of HomeController.

Index.cshtml

@using(Html.BeginForm("Save", "Home", FormMethod.Post, 
               new {enctype = "multipart/form-data"}))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit"/>
            </td>
        </tr>
    </table>
}

Notice the two additional parameters for BeginForm

FormMethod.Post, new {enctype = "multipart/form-data"}

You need those to have the file included in the HTTP Post action to the Save method on the controller. Other than that, you just need a file input control, with a unique name attribute set.

HomeController

using System;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Save(FormCollection formCollection)
        {
            if(Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if((file != null) && (file.ContentLength > 0) && 
                   !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileBytes, 0, 
                                       Convert.ToInt32(file.ContentLength));

                    string pth = Path.GetFileName(fileName);
                    // change the folder
                    file.SaveAs(Server.MapPath("~/Uploads") + "/" + pth);
                }
            }

            return View("Index");
        }
    }
}

The Request object is a base object for handling HTTP requests. Since we set the FormMethod and enctype in the view, we have access to the file that was submitted on the page.

If the Request object isn’t null, we can check for the file by getting the HttpPostedFileBase from the Request object’s list of files, using its name (which is why a unique name was required for the file input control on the view).

Then we do some checking, to make sure the file actually has data, and get its information.

If you’re going to save the files somewhere (which is probably why you’re letting people upload files), then you’re going to need a way to display it for them later. To display a file within a browser, you need to know its ContentType. This will let the browser display it in the correct way.

With the byte array of the file’s contents, you can either save it to the database, in a varbinary column [for SQL Server], or write it out to disk, or some other document storage location.

Where you should save the files depends on what you’re going to do with them, how large they are, and what type of file they are.

If you see an error like

The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

the problem is in the SaveAs function. You must pass a valid full path such as “C:\Uploads\Test\1.png”. For this reason I created in the root of the project a folder called Uploads and use Server.MapPath to find the full path.

Happy coding!

Advertsing

125X125_06

TagCloud

MonthList

CommentList