MVC 4 Razor File Uploading

Posted on April 6, 2018 by Suresh Kamrushi in

Sharing simple and basic code using which we can easily upload a single file to the server. You can add validation before you move to production server as the code does not validate the file type. One should validate file type before moving to production server as a user can upload any unwanted file to the server and take control over the server data.

HTML: [You can place below code in view folder]

<form method="post" name="exportData" action="~/ControllerName/saveFile" enctype = "multipart/form-data" >
<div>File :</div>
<input name="file" id="file" type="file">
<input type="submit" id="upload" name="upload" />

Server :[You can add below code in controller]

public ActionResult saveFile(HttpPostedFileBase file)
    if (file != null && file.ContentLength > 0)
        string folderPath = System.Configuration.ConfigurationManager.AppSettings.Get("expimp_folder");
        var fileName = Path.GetFileName(file.FileName);
        var path = folderPath+"/"+fileName;
    return new EmptyResult();

Hope it will help someone!!!

  Comments or questions are welcome  

Tagged as ,