3

I want to upload file using ajax to an ASP.Net MVC Controller

My JavaScript code looks like this, basically every time the user changed the input value, it will automatically upload the file to the controller

var formdata = false;
if (window.FormData) {
    formdata = new FormData();
}

$('input[name=default_export_filename]').change(function() {
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];
        if (file.type.match(/spreadsheet/) || file.type.match(/ms-excel/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    //showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("default_export_filename", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: root + mod + '/uploaddef',
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                console.log(res);
            }
        });
    }
});

In the controller side, I couldn't catch that file using this

    [HttpPost]
    public ActionResult UploadDEF(HttpPostedFileBase file)
    {
        var jsonData = new
        {
            response = 3
        };

        return Json(jsonData); ;
    }

Or this

    [HttpPost]
    public ActionResult UploadDEF(FormCollectionfile)
    {
        var jsonData = new
        {
            response = 3
        };

        return Json(jsonData); ;
    }

The file argument is always null. But in the firebug, I can see that the browser is posting the file to the server. With what object should I catch the file?

I realize the FormData object is not supported in older browser, but my clients are all using the latest browser. So that is not a problem.

strike_noir
  • 4,080
  • 11
  • 57
  • 100

2 Answers2

3

The problem is solved.

It turns out I don't have to give any parameters to the controller's method. The files are available through Request object.

Thanks all

strike_noir
  • 4,080
  • 11
  • 57
  • 100
1

You can't use ajax POST to upload a file like this, must be a form submit.

Have a look at component like AjaxUploadify or similar.

dove
  • 20,469
  • 14
  • 82
  • 108
  • it worked with PHP http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/ – strike_noir Oct 09 '12 at 11:39
  • @strike_noir apparently it is restricted for security reasons. ajax does not allow multipart/form-data enctype. there are several solutions, most using an iframe, that get around this – dove Oct 09 '12 at 12:17
  • I found the solution , AJAX file upload in ASP.Net MVC works, thanks anyway – strike_noir Oct 09 '12 at 14:09