是否可以在操作中发布IFormCollection和对象?
public Task CreateEMail(IFormCollection collection, [FromBody] Model model)
我尝试从Angular向WebAPI发出发布请求,该请求是上载文件和模型的组合。
角度代码:
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代码:
public Task CreateEMail(IFormCollection collection, [FromBody] Model model)
{
...
}
如何实现此WebAPI?
更新:我正在考虑将所有内容添加到FormCollection中,但这对于解析数据确实是不好的代码
答案 0 :(得分:2)
您只能将单个内容值发布到Web API Action方法。试试这个:
角度代码:
<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代码:
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();
}
此外,您可以使用自定义参数绑定,例如JObject,FormDataCollection或查询字符串。
希望有帮助。