[英]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.