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?

CJH
  • 1,266
  • 2
  • 27
  • 61
  • https://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/ – Chetan Mar 16 '20 at 21:47
  • Does this answer your question? [jQuery ajax upload file in asp.net mvc](https://stackoverflow.com/questions/2428296/jquery-ajax-upload-file-in-asp-net-mvc) – Chetan Mar 16 '20 at 21:48
  • This does look promising actually....! I will probably take a look in the morning and will update! Many thanks for the quick response...! Really appreciate it! :) – CJH Mar 16 '20 at 21:49
  • https://stackoverflow.com/questions/44475698/how-to-upload-files-using-ajax-call-in-asp-net – Chetan Mar 16 '20 at 21:49

1 Answers1

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
        }

    }
Train
  • 3,420
  • 2
  • 29
  • 59
  • 1
    Thanks - this and a couple of other similar suggestions have gotten this working for me. – CJH Mar 17 '20 at 10:12