WebAPI Is it possible to post an IFormCollection and Object in an action?

后端 未结 1 1164
天涯浪人
天涯浪人 2021-01-26 03:46

Is it possible to post an IFormCollection and Object in an action?

public Task CreateEMail(IFormCollection collection, [FromBody] Model model)

相关标签:
1条回答
  • 2021-01-26 04:18

    You can only post a single content value to a Web API Action method. Try this:

    Angular code:

    <input type="file" name="uploadFiles" (change)="onSelectFile($event)" />
    onSelectFile(event: any) {
            const fi = event.srcElement;
            if (fi.files && fi.files[0]) {
                const fileToUpload = fi.files[0];
                const formData = new FormData();
                const model = new Model('name', 'email@gmail.com');
                formData.append(fileToUpload.name, fileToUpload);
                console.log(JSON.stringify(model));
                formData.append('model', JSON.stringify(model));
                this.http.post(this.requestUploadURL, formData).subscribe();
            }
    }
    

    Web Api Code:

    public async Task<IActionResult> UploadFile()
    {
         var formFile = Request.Form.Files?.FirstOrDefault();
         var canParse = Request.Form.TryGetValue("model", out var model);
         if (canParse)
         {
              var data = JsonConvert.DeserializeObject<Model>(model.ToString());
         }
    
         return Ok();
    }
    

    Furthermore, you can use custom parameter binding such as JObject, FormDataCollection or Query String.

    Hope it's helpful.

    0 讨论(0)
提交回复
热议问题