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

前端 未结 2 1109
情歌与酒
情歌与酒 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:28

    Read answer fron maherjendoubi here : https://forums.asp.net/t/2099194.aspx?Net+Core+Web+API+How+to+upload+multi+part+form+data

    public ActionResult CreateDocument()
    {
          foreach(var key in Request.Form.Keys)
            {
                var data = JsonConvert.DeserializeObject(Request.Form[key]);
                var file = Request.Form.Files["file" + key];
    
            }
            return Ok();
        }
    

    For the angular part use an HttpRequest:

    const sendable = new FormData();
    
    for (let i; i < files.length; i++) {
        sendable.append('filedata' + i, files[i], files[i].name);
        sendable.append('data' + i, JSON.stringify(data[i]));
    }
    const request = new HttpRequest(item.method,
          item.url,
          sendable,
          {
            reportProgress: true
          });
    // this._http: HttpClient
    this._http.request(request)
          .subscribe((event: any) => {
            if (event.type === HttpEventType.UploadProgress) {
              // on progress code
            }
            if (event.type === HttpEventType.Response) {
              // on response code
            }
          }, error => {
            // on error code
          });
    

提交回复
热议问题