到达API核心3.1时,formData始终为null

时间:2020-01-30 15:21:17

标签: c# angular .net-core

尝试使用FormData将图像上传到我的后端。使用我的角度代码时,API中的文件始终为空。

创建FormData:

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);
    })
}

执行帖子调用的服务

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上传图片时使用,而不使用角度代码时使用。

编辑:

在这里找到正确的答案: https://stackoverflow.com/a/35325907/7128762

问题基本上是我需要在控制器中给IFormFile正确的名称。

1 个答案:

答案 0 :(得分:0)

[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
}