[英]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.