2

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?

3

5 Answers 5

8

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>
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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
}

4 Comments

it doesnot call the controller action @Jitendra Pancholi
@JasperManickaraj: Have you updated your html as per mine and copy pasted the js correctly ?
@JasperManickaraj: You must have done some mistake becuase i tested this code on my machine.
Can u give me ur emailid @Jitendra Pancholi
0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.