简体   繁体   English

如何在ASP.NET Core控制器中接收文件

[英]How to receive a file in ASP.NET Core controller

I want to send an image with C# HttpClient, receive it in ASP.NET Core controller and save it to disk. 我想使用C#HttpClient发送图像,在ASP.NET Core控制器中接收它并将其保存到磁盘。 I tried various methods but all i'm getting in controller is null reference. 我尝试了各种方法,但我在控制器中获得的只是null引用。

My http client: 我的http客户端:

public class HttpClientAdapter
{
    private readonly HttpClient _client;

    public HttpClientAdapter()
    {
        _client = new HttpClient();
    }

    public async Task<HttpResponse> PostFileAsync(string url, string filePath)
    {
        var requestContent = ConstructRequestContent(filePath);
        var response = await _client.PostAsync(url, requestContent);
        var responseBody = await response.Content.ReadAsStringAsync();

        return new HttpResponse
        {
            StatusCode = response.StatusCode,
            Body = JsonConvert.DeserializeObject<JObject>(responseBody)
        };
    }

    private MultipartFormDataContent ConstructRequestContent(string filePath)
    {
        var content = new MultipartFormDataContent();
        var fileStream = File.OpenRead(filePath);
        var streamContent = new StreamContent(fileStream);
        var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
        imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
        content.Add(imageContent, "image", Path.GetFileName(filePath));
        return content;
    }
}

and controller: 和控制器:

[Route("api/files")]
public class FilesController: Controller
{
    private readonly ILogger<FilesController> _logger;

    public FilesController(ILogger<FilesController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IActionResult Post(IFormFile file)
    {

        _logger.LogInformation(file.ToString());
        return Ok();
    }
}

As i mentioned above, the IFormFile object i'm getting in the controller is null reference. 如上所述,我在控制器中获取的IFormFile对象为空引用。 I tried adding [FromBody], [FromForm], tried creating class with two properties: one of type string and one with type IFormFile, but nothing works. 我尝试添加[FromBody],[FromForm],并尝试创建具有两个属性的类:一个类型为字符串,另一个类型为IFormFile,但是没有任何效果。 Also instead of sending file with C# HttpClient i used Postman - same thing happens. 另外,我不是使用C#HttpClient发送文件,而是使用邮递员-会发生同样的事情。

Does anyone know solution for this problem? 有谁知道解决这个问题的方法吗? Thanks in advance. 提前致谢。

The name of the form field must match the property name: 表单字段的名称必须与属性名称匹配:

content.Add(imageContent, "file", Path.GetFileName(filePath));

file instead of image , since you use file in 文件 ,而不是图像 ,因为您在使用文件

public IActionResult Post(IFormFile file)
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将文件上传到 ASP.NET 内核 controller? - How to upload file to an ASP.NET Core controller? 如何在ASP.NET Core Web API控制器中接收字节数组和标头内容 - How to receive a byte array and header content in a ASP.NET Core Web API Controller 如何使用asp.net核心在action方法中接收通过ajax请求发送的文件和整数 - How to receive a file and an integer sent through an ajax request in action method using asp.net core 如何接收发布到 ASP.net 核心 2.1 Web-API 端点的文件和数据 - How to receive both File and data POSTed to an ASP.net core 2.1 Web-API endpoint 如何在 API 调用 ASP.NET Core 时接收 json 值 - how to receive json values on API call in ASP.NET Core ASP.NET Core 中间件打破物理文件控制器方法 - ASP.NET Core Middleware Breaks Physical File Controller Method 文件未按预期在 Asp.Net Core controller 中流式传输 - File not streaming as expected in Asp.Net Core controller 如何在 ASP.NET Core 中下载文件? - How to download a file in ASP.NET Core? 如何将图像文件发布到 asp.net core 5 中的 api 控制器? (415 错误) - how do you post an image file to an api controller in asp.net core 5? (415 error) 如何将文件中的其他参数从 Angular 传递到 ASP.NET Core controller? - How to pass other parameter with file to ASP.NET Core controller from Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM