How to upload a file using ASP.NET MVC C#

In this example, I'm going to show you how to use the ASP.NET FileUpload tag. By now, It is assumed you have created your solution and you have a view and a controller in place ready for the upload page. In the view, we will add the following HTML.

@{ ViewBag.Title = "Index"; }
<h2>UploadFile</h2>

@using (Html.BeginForm("Index", "UploadFile", FormMethod.Post,new { enctype = "multipart/form-data" }))
    {
    <label for="file">Upload File:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" value="Upload" />

    @ViewBag.Message
    }

We then need to amend the Controller code so that we can save the functionality. We are are only needing a filename back so we don't have to accept a model, just an individual parameter is needed in code.

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    try
    {
        // Get the filename of where we are going to store the file
        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));

        file.SaveAs(path);
        ViewBag.Message = "File uploaded successfully";
    }
    catch (Exception ex)
    {
        ViewBag.Message = "ERROR:" + ex.Message.ToString();
    }
    else
    {
        ViewBag.Message = "You have not specified a file.";
    }
    return View();
}

If things have worked out well, you will not have a file located in your UploadedFiles directory. After the file has been uploaded, you can do what you want after.

Tags - .NET   FTP

Last Modified : June 2023


About... / Contact.. / Cookie...