[英]How can I post a json object and a file to asp.net server with fetch
I'm a bit stuck here, I'm trying to post a json object from my indexedDb simultaneously with a IFormFile object to the server. 我在这里有点卡住,我试图同时将indexedDb中的json对象和IFormFile对象发布到服务器。 The method that accepts it looks like this: 接受它的方法如下所示:
[HttpPost]
public async Task<IActionResult> Create(BatchModel model, IFormFile vinFile)
{
//logic goes here
}
This method worked earlier, before I had to store my batchModels as Json objects, and were just posted straight from the form with a POST. 在不得不将我的batchModels存储为Json对象之前,此方法已经开始起作用,并且只是通过POST从表单直接发布。 A lot has changed since then, and now the client will upload it as soon as he gets online again from an offline state, with the following (simplified) method: 此后发生了很多变化,现在客户端将通过离线(简化)方法将其从离线状态恢复为在线状态后立即上传:
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);
For testing I tried to use the method with only the model filled, and the only thing I had to change was that I had to change in the C# code was adding a [FromBody] tag, but now I need the vinFile filled as well. 为了进行测试,我尝试仅在模型填充的情况下使用该方法,而我唯一需要更改的是,我必须在C#代码中进行的更改是添加[FromBody]标记,但是现在我也需要填充vinFile。 I tried it already with a FormData object, appending the batch and the vinFile with the same name as in the Create function. 我已经使用FormData对象进行了尝试,将批处理和vinFile附加了与Create函数中相同的名称。 But that would result in both variables as null. 但这将导致两个变量均为null。
The key feature you need to look at is your header. 您需要查看的关键功能是标题。 You can change your response to JSON if you do header: { Content-Type: "application/json" } 如果执行标头,则可以更改对JSON的响应:{Content-Type:“ application / json”}
You want something like this: You need to configure the type yourself. 您想要这样的事情:您需要自己配置类型。
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/en-US/docs/Web/API/Fetch_API/Using_Fetch https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.