Jasper Manickaraj
Jasper Manickaraj

Reputation: 837

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?

Upvotes: 2

Views: 43792

Answers (5)

Jitendra Pancholi
Jitendra Pancholi

Reputation: 7562

Below code will do a full post back in an hidden form which will give an illusion of ajax file upload. Try it:

Update:

JS

function Upload(sender) {
    var iframe = $("<iframe>").hide();
    var newForm = $("<FORM>");
    newForm.attr({ method: "POST", enctype: "multipart/form-data", action: "/ControllerName/Final" });        
    var $this = $(sender), $clone = $this.clone();
    $this.after($clone).appendTo($(newForm));
    iframe.appendTo($("html")).contents().find('body').html($(newForm));
    newForm.submit();
}

HTML

<input type="file" id="Uploadfile" name="Uploadfile" />
<input type="button" onclick="Upload($('#UploadFile'));"/>

Controller

public ActionResult Final(HttpPostedFileBase Uploadfile)
{
     //here you can use uploaded file
}

Upvotes: 1

Biki
Biki

Reputation: 2588

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>
}

Upvotes: 8

Soner Sevinc
Soner Sevinc

Reputation: 400

You can do it by using json data to view.

As instance,

Controller

public ActionResult Products(string categoryid)
{
List<catProducts> lst = bindProducts(categoryid);
return View(lst);
}   
public JsonResult Productsview(string categoryid)
{
//write your logic
var Data = new { ok = true, catid = categoryid};
return  Json(Data, JsonRequestBehavior.AllowGet);
}

View:

@{
ViewBag.Title = "Index";
}

@model ASP.NETMVC.Controllers.Categories

<h2>List Of Categories</h2>

@Html.ListBox("lst_categories", (IEnumerable<SelectListItem>)  ViewBag.Categories)


<script type="text/javascript">
$(function () {

$('#lst_categories').change(function () {

var catid = $('#lst_categories :selected').val();

$.ajax({
url: '@Url.Action("Productsview", "Jquery")',
type: 'GET',
dataType: 'json',
data: { categoryid: catid },
cache: false,

success: function (Data) {
if (Data.ok) {

var link = "@Url.Action("Products", "Jquery", new { categoryid = "catid" })";
link = link.replace("catid", Data.catid);
alert(link);
window.location.href = link;
}
}
});
});
});
</script>

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

As a completion from Ravi's answer, I would suggest to use the following using statement:

@using(Html.BeginForm("yourAction","YourControl",FormMethod.Post, new { enctype="multipart/form-data" }))
{
   <input type="file" id="fileUpload" />
}

Upvotes: 0

Ravi Gadag
Ravi Gadag

Reputation: 15861

you cannot send file content via javascript (unless HTMl5). and you are doing totally wrong. if you want to do HTML5 based solution via FileReader api then you need to check this out. FileReader Api

Just put a form tag and use the same name of the input in the controller action to perform model binding

@using(Html.BeginForm("yourAction","YourControl",FormMethod.Post))
{
 <input type="file" id="fileUpload" />
}

then in controller.

[HTTPPost]
public ActionResult Final(HttpPostedFileBase fileUpload)
  {
     //here i have got the files value is null.
  }

Upvotes: 3

Related Questions