简体   繁体   中英

Access file using MVC 6 .NET Core with ajax

I am calling this function to send a file via post:

function AddFileHandler() {
        return $.ajax({
            processData: false,
            contentType: false,
            type: "POST",
            url: '@Url.Action("AddFile", "SomeController")',
            data: getFile()
        })
    }

In my controller, there is this method which produces an error on the first line:

[HttpPost]
public string AddFile()
{
    var attachedFile = Request.Form.Files["CsvDoc"]; // there is an error of wrong contentType
    return "";
}

My getFile method optains data like this:

function getFile() {
    var input = document.getElementById("csvFile");
    if (!input || !input.files || !input.files[0]) {
        return ";";
    }
    console.log(input.files[0]); //inputs my file correctly
    var data = new FormData();
    data.append("CsvDoc", input.files[0]);
}

What exactly am I doing wrong? Does it matter what is in the html?

You're forgetting to return anything from getFile()

simply add

return data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM