Javascript 将文件(FormData)上载到WebApi
我正在尝试将文件上载到WebApi,但没有收到该文件。我也不知道文件是否被追加。我正在这样做:Javascript 将文件(FormData)上载到WebApi,javascript,ajax,asp.net-web-api,file-upload,Javascript,Ajax,Asp.net Web Api,File Upload,我正在尝试将文件上载到WebApi,但没有收到该文件。我也不知道文件是否被追加。我正在这样做: if (this.state.file) { var file = this.state.file; if (window.FormData !== undefined) { var data = new FormData(); data.append("file", file);
if (this.state.file) {
var file = this.state.file;
if (window.FormData !== undefined) {
var data = new FormData();
data.append("file", file);
$.ajax({
type: "POST",
url: "/api/service/upload",
contentType: "text/csv",
processData: false,
data: data,
success: function (result) {
console.log(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
}
}
另外,为了检查请求负载的内容,我尝试了以下方法,而不是Ajax调用:
var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.setRequestHeader('Content-Type', 'text/csv');
xhr.send(data);
并且只显示:
------WebKitFormBoundary6xZnDkSOxBAxaovA内容配置:表单数据;name=“file”;filename=“Teste.csv”内容类型:
应用程序/vnd.ms-excel
------WebKitFormBoundary6xZnDkSOxBAxaovA--
如果文件大小不大,可以使用base64编码。将编码的字符串数据发送到web api服务。解码并使用它。好的,这样你就有了一个文件对象,它看起来是正确的。试试下面的代码
var file; // Assuming this is the file object.
var formData = new FormData();
formData.append('file', file);
$.ajax({
type : 'POST',
url : '/api/service/upload',
data : formData,
dataType : 'json', // json, html whatever you like.
contentType: false, // Change this line
processData: false
}).done(function(res) {
console.log(res);
}).fail(function(res) {
console.log(res.responseText);
});
如果您在api服务中使用PHP。您应该能够使用打印($\u文件)
并在那里查看文件
希望这有帮助。尝试从ajax调用中删除
contentType
选项。另外,请验证此.state.file
是一个文件对象,而不是一个文件对象数组console.log
it.I得到这个(我猜是一个文件对象):file{name:“Teste.csv”,lastModified:1491903259490,lastModifiedDate:2017年4月11日星期二10:34:19 GMT+0100(GMT夏令时),webkitRelativePath:,size:32…}lastModified:1491903259490 lastModifiedDate:2017年4月11日星期二10:34:19 GMT+0100(GMT夏令时)name:“Teste.csv”大小:32类型:“application/vnd.ms excel”webkitRelativePath:“proto”:文件但在我将文件附加到FormData对象后,该对象只有原型,这正常吗?里面不应该有文件对象吗?这很正常。我正在为这篇文章准备一个带有代码的答案。试试看。