2

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?

4

1 Answer 1

3

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
        }

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

1 Comment

Thanks - this and a couple of other similar suggestions have gotten this working for me.

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.