![](/img/trans.png)
[英]ASP.Net Core 3.1 - Post parameter is always NULL in Web API
[英]formData is always null when arriving in API core 3.1
嘗試使用 FormData 將圖像上傳到我的后端。 使用我的角度代碼時,我的 API 中的文件始終為空。
創建表單數據:
upload() {
let formData = new FormData();
formData.append('upload', this.editedImage);
console.log("editedImage: " + this.editedImage);
console.log("formdata: " + formData);
this.imageService.create(formData).subscribe(response => {
let temp = response;
console.log(temp);
})
}
執行 post 調用的服務:
create(formData: FormData): Observable<any> {
console.log("formdata in service: " + formData.get('upload'));
return this.http.post<any>(`${this.url}`, formData).pipe(
tap(data => console.log('Image verstuurd: ' + data)),
catchError(this.handleError)
);
}
接收它的 API:
[HttpPost]
async public Task<ActionResult> Save([FromForm]IFormFile file)
{
// Get reference to blob
var uniqueName = $@"{Guid.NewGuid()}-{file.FileName}";
CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(uniqueName);
using var ms = new MemoryStream();
file.CopyTo(ms);
var stream = ms.ToArray();
await blockBlob.UploadFromByteArrayAsync(stream, 0, stream.Length);
return Json(new
{
name = blockBlob.Name,
uri = blockBlob.Uri
});
}
當我使用 Postman 上傳圖像時它有效,而不是使用 angular 代碼時。
編輯:
正確答案在這里找到: https : //stackoverflow.com/a/35325907/7128762
問題基本上是我需要在我的控制器中為我的 IFormFile 提供正確的名稱。
[FromForm] 將嘗試為其接收的表單數據構建一個引用類型,因此您的 FormFile 需要位於您定義的引用類型內。
用這樣的東西設置你的模型:
public class YourDataModel
{
public IFormFile File { get; set; }
// whatever other properties you need
}
在你的 API 控制器中嘗試這樣的事情:
[HttpPost]
async public Task<ActionResult> Save([FromForm]YourDataModel file)
{
// your logic
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.