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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

@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
I found the solution , AJAX file upload in ASP.Net MVC works, thanks anyway

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.