0

I have a HTML Razor View Like this:

@using (Html.BeginForm("Insert", "Operation", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data", id = "image_form" }))
{
   <div>
        <span class="btn btn-default ">
        <span class="fileinput-new">Up Your Image</span>
        <input type="file" name="nationalCard" id="nationalCard">
        </span>
  </div>
  <input type="button" class="btn btn-default" id="submit_image" onclick="insert()" value="ثبت" />
}

My Jquery Ajax codes are:

 function insert() {
    var formData = $("#image_form");
    $.ajax({
        type: "POST",
        url: '@Url.Action("Insert", "Operation")',
        data: formData.serialize(),
        dataType: "json",
        success: function (data) {
            //do something...
        },
    });
};

So I want to receive image in action controller Based on Request object and Files property like this :

 [HttpPost]
 public ActionResult Insert()
 {
   if (Request.Files.Count > 0)
   {
      var image = Request.Files["nationalCard"];
      //do something...
   }
 }

I have tried this and in action didn't receive file.any idea who can I do that?

fbarikzehy
  • 4,885
  • 2
  • 33
  • 39
  • you added the `multipart/form-data` to your `BeginForm` but you're handling the post with ajax so you need to add `enctype: 'multipart/form-data'` to your ajax call. look at these answers for more help http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload?answertab=oldest#tab-top I'd look at some of the more recent answers and not just the accepted answer – JamieD77 Jul 31 '15 at 16:31
  • Thanks but I have overview the link and tried this:'enctype: 'multipart/form-data' but still not working. – fbarikzehy Jul 31 '15 at 16:59

3 Answers3

2

The first problem I see is that your action name does not match the action in your jQuery AJAX call.

 url: '@Url.Action("Insert", "Operation")',

needs to be changed to

 url: '@Url.Action("InsertIdentification", "Operation")',

EDIT

Now that your methods match ( here at least ) we can try this. I added this in my Javascript file for my site. I can't find the source but I am pretty sure that I found it here on SO. There is a difficulty with uploading files via AJAX apparently and this script overcomes that by modifying the XHR object. I use it with the built in Ajax.BeginForm and it works great.

$(document).ready(function(){
 window.addEventListener("submit", function (e)
{
    var form = e.target;
    if (form.getAttribute("enctype") === "multipart/form-data")
    {
        if (form.dataset.ajax)
        {
            e.preventDefault();
            e.stopImmediatePropagation();
            var xhr = new XMLHttpRequest();
            xhr.open(form.method, form.action);
            xhr.onreadystatechange = function ()
            {
                if (xhr.readyState == 4 && xhr.status == 200)
                {
                    if (form.dataset.ajaxUpdate)
                    {
                        var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        if (updateTarget)
                        {
                           //this is where you update your view or partial view
                            updateTarget.innerHTML = xhr.responseText;
                            $(":file").filestyle({ buttonBefore: true, buttonName: "btn btn-default", buttonText: "Browse" });
                        }
                    }
                }
            };
            xhr.send(new FormData(form));
        }
    }
}, true);

});

I also use HttpPostedFileBase file as a parameter of my action to access the file contents.

[HttpPost]
public ActionResult Insert(HttpPostedFileBase file)
{
   //do work with your file here...
}
Trucktech
  • 328
  • 1
  • 11
1

If you already fix the problem with the routing etc ...

You need to do the following in order to upload a file asynchronously :

function uploadFileAjax(){
     var inputFileImage = document.getElementById("nationalCard"); // or $("#nationalCard")[0]
var file = inputFileImage.files[0];
var data = new FormData();
data.append('archivo',file);
$.ajax({
    url:"magicpath.php",
    type:"post",
    contentType:false,
    data:data,
    processData:false,
    cache:false,
    dataType:"json",
    success:function(data){
        console.log(data);
    },
    error:function(data){
        console.log(data);
    }
});
}

This should succesfully upload the file to your php script. Depends on your script how to move it etc ..

Carlos Delgado
  • 2,930
  • 4
  • 23
  • 49
1

Just setting processData and contentType to false should do the trick:

function insert() {
    var reader = new FileReader();

    var selectedImage = document.getElementById('nationalCard').files[i];

    var formData = new FormData();
    formData.append('file', input.files[0]);

    $.ajax({
         url: '@Url.Action("Insert", "Operation")',
         data: formData ,
         type: 'POST',
         processData: false,
         contentType: false,
         success: function (result) { alert (result); }
   });
};

Now it will be available in your action method:

 [HttpPost]
 public ActionResult Insert()
 {
   if (Request.Files.Count > 0)
   {
      var image = Request.Files[0];
      //do something...
   }
 }

Here processData as per jQuery means the following:

By default, data passed in to the data option as an object (technically,
anything other than a string) will be processed and transformed into a query
string, fitting to the default content-type "application/x-www-form-urlencoded". 
If you want to send a DOMDocument, or other non-processed data, set this option to false.

As of jQuery 1.6 you can pass false to **contentType** to tell jQuery to not set any content type header.
Aamir
  • 1,747
  • 5
  • 26
  • 50