[英]How to use IFormFile as property when uploading file to a server using Asp.NET Core 3.1 framework?
我正在尝试创建一个可以处理存储文件的 Web API。
Asp.Net 核心 1.0+ 框架附带IFormFile接口,允许将文件绑定到视图模型。 有关在 ASP.NET Core 中上传文件的文档说明如下
IFormFile可以直接用作操作方法参数或绑定模型属性。
当我使用IFormFile
作为操作方法的参数时,它没有问题。 但就我而言,我想将它用作模型上的属性,因为除了包含自定义验证规则之外,我还想绑定其他值。 这是我的视图模型。
public class NewFile
{
[Required]
[MinFileSize(125), MaxFileSize(5 * 1024 * 1024)]
[AllowedExtensions(new[] { ".jpg", ".png", ".gif", ".jpeg", ".tiff" })]
public IFormFile File { get; set; }
[Required]
public int? CustomField1 { get; set; }
[Required]
public int? CustomField2 { get; set; }
[Required]
public int? CustomField3 { get; set; }
}
这是我的客户端请求和接受文件的服务器代码的代码。 为简单起见,这两种方法都放在同一个控制器中。 但实际上,“客户端”方法将放置在发送文件的单独应用程序中。
[ApiController, Route("api/[controller]")]
public class FilesController : ControllerBase
{
[HttpGet("client")]
public async Task<IActionResult> Client()
{
using HttpClient client = new HttpClient();
// we need to send a request with multipart/form-data
var multiForm = new MultipartFormDataContent
{
// add API method parameters
{ new StringContent("CustomField1"), "1" },
{ new StringContent("CustomField2"), "1234" },
{ new StringContent("CustomField3"), "5" },
};
// add file and directly upload it
using FileStream fs = System.IO.File.OpenRead("C:/1.jpg");
multiForm.Add(new StreamContent(fs), "file", "1.jpg");
// send request to API
var responce = await client.PostAsync("https://localhost:123/api/files/store", multiForm);
return Content("Done");
}
[HttpPost("store")]
public async Task<IActionResult> Store(NewFile model)
{
if (ModelState.IsValid)
{
try
{
var filename = MakeFileName(model, Path.GetFileName(model.File.FileName));
Directory.CreateDirectory(Path.GetDirectoryName(filename));
using var stream = new FileStream(filename, FileMode.Create);
await model.File.CopyToAsync(stream);
return PhysicalFile(filename, "application/octet-stream");
}
catch (Exception e)
{
return Problem(e.Message);
}
}
// Are there a better way to display validation errors when using Web API?
var errors = string.Join("; ", ModelState.Values.SelectMany(v => v.Errors).Select(v => v.ErrorMessage));
return Problem(errors);
}
}
当我发出请求时,我收到以下错误,但请求从未到达store
方法,因为我在那里放置了一个断点,但它从未到达那里。
状态代码:415,原因短语:“不支持的媒体类型”,版本:1.1,内容:System.Net.Http.HttpConnectionResponseContent
如何正确地将文件发送到服务器并将其绑定到我的视图模型上的File
属性?
默认情况下, ApiController
需要 JSON,除非另有明确说明
使用[FromForm]
在请求正文中使用表单数据绑定模型。
public async Task<IActionResult> Store([FromForm]NewFile model) {
//...
}.
CustomField1、CustomField2 和 CustomField3` 为空,即使它们被发送,如您在我的原始问题中所见
客户端没有正确发送那些其他字段。 您已切换内容和字段名称
var multiForm = new MultipartFormDataContent {
// add API method parameters
{ new StringContent("1"), "CustomField1" },
{ new StringContent("1234"), "CustomField2" },
{ new StringContent("5"), "CustomField3" },
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.