[使用Asp.NET Core 3.1框架将文件上传到服务器时如何使用IFormFile作为属性?

问题描述 投票:2回答:1

我正在尝试创建一个处理存储文件的Web API。

Asp.Net core 1.0+框架附带IFormFile接口,该接口允许将文件绑定到视图模型。 documentation about uploading files in 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方法。

StatusCode:415,ReasonPhrase:“不受支持的媒体类型”,版本:1.1,内容:System.Net.Http.HttpConnectionResponseContent

如何正确将文件发送到服务器并将其绑定到我的视图模型上的File属性?

c# asp.net-core asp.net-core-2.0 asp.net-core-webapi asp.net-core-3.0
1个回答
1
投票

[ApiController默认情况下需要JSON,除非另有明确说明

使用[FromForm]使用请求正文中的表单数据绑定模型。

[FromForm]

参考public async Task<IActionResult> Store([FromForm]NewFile model) { //... }.

CustomField1,CustomField2和CustomField3`为空,即使您按照我在原始问题中看到的那样发送它们也是如此

客户端未正确发送其他字段。您已切换了内容和字段名称

Model Binding in ASP.NET Core
© www.soinside.com 2019 - 2024. All rights reserved.