简体   繁体   中英

Sending a file from an html input to a WebApi with Ajax - Encoding issue

I have a input tag with type="file" and a function that uses Ajax to send the file to a Webapi endpoint.

$('#myInput').change(function () {
    if (this.files[0] === undefined) return;
    sendToWebapi(this.files[0]);
    this.value = null;
});

function sendToWebapi(file) {
    const data = new FormData();
    data.append('file', file);
    $.ajax({
        url: "myWebApiPath",
        contentType: "text/csv",
        processData: false,
        method: "POST",
        data: data
    });
}

My issue is that French characters are not properly encoded when sent to the WebApi. See below an extract of the Request Body:

> ------WebKitFormBoundaryggBmtBMylhc9eoIE
Content-Disposition: form-data; name="file"; filename="myfile.csv"
Content-Type: application/vnd.ms-excel

Date;Pi�ce;Journal;Libell�;D�bit;Lettrage;Cr�dit;Solde
....

Try setting charset explicitly:

function sendToWebapi(file) {
    const data = new FormData();
    data.append('file', file);
    $.ajax({
        url: "myWebApiPath",
        contentType: "text/csv;charset=ISO-8859-1",
        processData: false,
        method: "POST",
        data: 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