[英]How can I post a json object and a file to asp.net server with fetch
我在这里有点卡住,我试图同时将indexedDb中的json对象和IFormFile对象发布到服务器。 接受它的方法如下所示:
[HttpPost]
public async Task<IActionResult> Create(BatchModel model, IFormFile vinFile)
{
//logic goes here
}
在不得不将我的batchModels存储为Json对象之前,此方法已经开始起作用,并且只是通过POST从表单直接发布。 此后发生了很多变化,现在客户端将通过离线(简化)方法将其从离线状态恢复为在线状态后立即上传:
if (infoChanged === true) {
fetchPromises.push(
fetch('/Batch/Create/', {
headers: new Headers({
'Content-Type': 'application/javascript' //Tried this with multi-part/form
}),
credentials: 'same-origin',
method: 'POST',
body: batch //, vinFile
})
);
}
return Promise.all(fetchPromises);
为了进行测试,我尝试仅在模型填充的情况下使用该方法,而我唯一需要更改的是,我必须在C#代码中进行的更改是添加[FromBody]标记,但是现在我也需要填充vinFile。 我已经使用FormData对象进行了尝试,将批处理和vinFile附加了与Create函数中相同的名称。 但这将导致两个变量均为null。
您需要查看的关键功能是标题。 如果执行标头,则可以更改对JSON的响应:{Content-Type:“ application / json”}
您想要这样的事情:您需要自己配置类型。
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); });
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.