如何使用fetch将json对象和文件发布到asp.net服务器

问题描述 投票:0回答:1

我有点卡在这里,我试图将我的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。

javascript asp.net json fetch
1个回答
0
投票

您需要关注的主要功能是标题。如果您执行标题,则可以更改对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/en-US/docs/Web/API/Fetch_API/Using_Fetch

© www.soinside.com 2019 - 2024. All rights reserved.