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

醉酒当歌 提交于 2019-12-24 19:32:00

问题


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

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

I try to make an post request to WebAPI from Angular and the request is a combination of uploaded files and a model.

Angular code:

let model = {title:'test', subject:'test'};
let formData = new FormData();
for (let i = 0; i < this.droppedFilesData.length; i++) {
    let file = this.droppedFilesData[i];
    let fileName = file.name;
    formData.append(fileName, file);
}
this.service.createEmail(formData, model); // how to implement to post formData and model

WebAPI Code:

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

How do I implement this WebAPI?

Update: I am thinking about adding everything into FormCollection but that would be really bad code to parse data


回答1:


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.



来源:https://stackoverflow.com/questions/53825794/webapi-is-it-possible-to-post-an-iformcollection-and-object-in-an-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!