forms - 无法在表单中同时发送文件和对象
问题描述
您好,我想知道您如何在表格中同时发送POCO
和发送files
。我的问题是双重的:
- 1.到目前为止,当我访问
Request.Form.Files[0]
并将其复制到文件中时,我得到了一个0kb
文件。 - 如果我想在我将用作我的方法的参数
MyPoco
时从我的表单中获取对象,我会得到一个不受支持的类型。[FromBody]
415
形式
<form id="createForm" method="post" enctype="multipart/form-data" action="http://localhost:8300/api/create">
<input type="text" bind="@model.Name"/>//some binding here
<input type="text" bind="@model.Id"/> //some binding...
<input type="file"/>
</form>
控制器
[HttpPost]
[Route("api/create")]
public async Task<long> CreateAsync([FromBody] MyPoco poco) { //getting error 415 when using the FromBody
try {
MyPoco poc = poco;
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"file.csv"); //copy the input file -> getting 0kb file
FileStream stream = new FileStream(path, FileMode.Create);
await this.Request.Form.Files[0].CopyToAsync(stream);
return 3;
} catch (Exception) {
return 0;
}
}
PS绑定的语法是,blazor
但在这种情况下并不重要。
解决方案
避免使用[FromBody]
,它将指示 ModelBinder 读取整个有效负载,然后将其序列化为MyPoco
.
为了实现您的目标,您可以如下声明您的操作方法:
[HttpPost("[action]")]
public IActionResult Test(MyPoco myPoco,IFormFile myfile){
// now you get the myfile file and the myPoco
}
然后发送具有完整名称的字段:
<form id="createForm" method="post" enctype="multipart/form-data" action="/api/SampleData/Test">
<input name="MyPoco.Name" type="text" bind="@model.Name" />
<input name="MyPoco.Id" type="text" bind="@model.Id" />
<input name="myfile" type="file" />
<button type="submit">submit this form</button>
</form>
演示截图:
推荐阅读
- spring-boot - JHipster Redis 排序集
- sql-server - 插入后触发
- python - Python:如何使用 __add__ 特殊方法添加返回该类的另一个实例的同一类的实例
- java - 引用的属性不是 (One|Many)ToOne: 在 mappedBy 中
- php - Woocommerce 产品/类别循环问题
- pandas - 加入后只保留一列
- docker - 使用 SpringBoot 和 MongoDB 运行 docker-compose 后找不到错误 404
- python - spark df中是否有可以被applymap替换的函数?
- java - 如何为测试启用“--enable-preview”?
- python - 为什么后面的 Python 函数定义在稍后调用时会产生“'NoneType' object is not subscriptable”错误?