-2

I have

[HttpPost]
public ActionResult GetFiles(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {            
        var fileName = Path.GetFileName(file.FileName);   
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }
    return Json("Uploaded " + Request.Files.Count + " files",JsonRequestBehavior.AllowGet);
}

Now I want to upload files in Ajax and save files another folder. How to get files from input form and send it via Ajax?

Christopher
  • 1,712
  • 2
  • 21
  • 50
Alexandr Sargsyan
  • 656
  • 1
  • 6
  • 21
  • You have not shown your ajax call. You need to use `FormData` is posting files using ajax. Refer [this example](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Sep 30 '15 at 08:46
  • I'm try it don't work. If you know working version please tell me – Alexandr Sargsyan Sep 30 '15 at 08:52
  • Tried what? You have not shown your code so how can we guess what you have done wrong –  Sep 30 '15 at 08:53
  • I'm trying multiple forms of FormData searching in internet. but my FormData aslo stayed empty, and I can't get it in my controller! – Alexandr Sargsyan Oct 01 '15 at 08:49

2 Answers2

0

Try this:

cshtml:

<input id="myFile" type="file" name="myfile" onchange="GoToPreview(this)" style="display: none">



function GoToPreview(input) {
            if (input.files && input.files[0]) {  

                var tmpImageData = new FileReader();
                tmpImageData.onload = function (e) {
                    SetImageData(imageData);                
                }
                tmpImageData.readAsDataURL(input.files[0]);
            }
    }

function SetImageData(imageData) {
        $.ajax({
            url: '/Home/SetImageData',
            type: 'POST',
            data: { imageData: imageData },
            success: function (data) {
                // code here
            },
            error: function (data) {
                // code for exception
            }
        });
    }

In SetImageData method at server side do your thing.

Gagan Jaura
  • 710
  • 1
  • 5
  • 14
0

As @Reza Aghaei already said you can use FormData to solve your problem, but i recommend you ajaxForm() method from this library. I use this approach becouse IE8 and IE9 do not support FormData

And it really is not difficult to use it.

Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70