从html输入发送文件到带有Ajax的WebApi - 编码问题
问题描述:
我有一个input
标签,type="file"
和一个使用Ajax将文件发送到Webapi端点的函数。
从html输入发送文件到带有Ajax的WebApi - 编码问题
$('#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
});
}
我的问题是,当发送到的WebAPI法国的字符不正确编码。请参见下面的请求体的摘录:
> ------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
....
答
尝试明确设置字符集:
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
});
}
注意,同时增加字符集明确导致了我的请求主体被正确显示,我的终点还是观看字符串作为前。 –
@François你的意思是“我的端点仍然像以前一样查看字符串”? – Oscar
Myenpoint签名是Task MyEndpointAsync([FromBody] List rows)。然后行中的每行都会看到像D bit这样的东西。 –