Passing an Excel file to server using AJAX Post

Viewed 3511

I simply want to be able to use a html Input type="file" to select an Excel file

<input type="file" id="UploadedFile" name="UploadedFile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">

then pass that chosen file back to the server - preferably using AJAX post:

    var serviceURL = appRoot + 'Register/ImportTasks'

    $j.ajax({
        type: "post",
        url: serviceURL,
        data: (??? Not sure how to present here ???),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

Specifically I cannot see how I present the 'file' to the AJAX call as data.

    public void ImportTasks(DataType?? uploadedExcelFile)
    {
        ..... Doing stuff ...
    }

And then I am unsure as to what parameter datatype I should then tell the Method to expect when it is called?

1 Answers

Here is a basic example. You should use FormData

     var formData = new FormData();
     var uploadFiles = document.getElementById('js-upload-files').files;
     this.formData.append("MyKey", uploadFiles[0]);

    $.ajax({
        type: "POST",
        url: 'Controller/Upload',
        data: formData,
        dataType: 'json',
        contentType: false,
        processData: false,
        complete: this.onComplete.bind(this)
    });

Edit

Forgot controller code

    [HttpPost]
    public virtual BetterJsonResult Upload()
    {

        foreach (var fileKey in Request.Files)
        {
            ...Request.Files[fileKey.ToString()] //access it like this
        }

    }
Related