Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send uploaded file from javascript to controller in MVC?

In my MVC, i have a view and that contains one file upload control and one button.

 <input type="file" id="Uploadfile" />
 <input type="button" onclick()="GetFile();/>

Javascript function as follows

function GetFile()
{
    var file_data = $("#Uploadfile").prop("files")[0];
    window.location.href="Calculation/Final?files="+file_data;
}

I need to pass/send the selected file via fileupload control to controller in mvc. I have the controller

public ActionResult Final(HttpPostedFileBase files)
{
    // here I have got the files value is null.
}

How to get the selected file and send it to the controller?

like image 890
Jasper Manickaraj Avatar asked Mar 24 '26 12:03

Jasper Manickaraj


1 Answers

I had similar functionality to deliver in my project. The working code looks something like this:

Controller Class

[HttpPost]
public ActionResult UploadFile(YourModel model1)
{
    foreach (string file in Request.Files)
    {
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
        if (hpf.ContentLength > 0)
        {
            string folderPath = Server.MapPath("~/ServerFolderPath");
            Directory.CreateDirectory(folderPath);

            string savedFileName = Server.MapPath("~/ServerFolderPath/" + hpf.FileName);
            hpf.SaveAs(savedFileName);
            return Content("File Uploaded Successfully");
        }
        else
        {
            return Content("Invalid File");
        }
        model1.Image = "~/ServerFolderPath/" + hpf.FileName;
    }

    //Refactor the code as per your need
    return View();
}

View

@using (@Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 <table style="border: solid thin; margin: 10px 10px 10px 10px">
     <tr style="margin-top: 10px">
         <td>
             @Html.Label("Select a File to Upload")
             <br />
             <br />
             <input type="file" name="myfile">
             <input type="submit" value="Upload" />
         </td>
     </tr>
 </table>
}
like image 108
Biki Avatar answered Mar 26 '26 02:03

Biki