How to upload data + multiple files from Angular to .net core Web Api

前端 未结 2 1112
情歌与酒
情歌与酒 2021-01-22 02:58

My server uses .Net Core 2.1.402

Here is my C# class:

public class SampleDetailsDto
{
    public Guid Id{ get; set; }
    public string Text { get; set;          


        
2条回答
  •  执念已碎
    2021-01-22 03:32

    Use IFormFile and [FromForm] and do not access the request to extract files.

    Angular code:

    public sendFiles(files: File[], [...]): Observable {
       const formData = new FormData();
       formData.append('files', files); // add all the other properties
       return this.http.post('http://somehost/someendpoint/fileupload/', formData);
    }
    

    ASP.NET Core code:

    public class MyFileUploadClass
    {
       public IFormFile[] Files { get; set; }
       // other properties
    }
    
    [HttpPost("fileupload")]
    public async Task FileUpload([FromForm] MyFileUploadClass @class)  // -> property name must same as formdata key
    {
       // do the magic here
       return NoContent();
    }
    

提交回复
热议问题