本文介绍了如何在ASP.NET Core Web API中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Asp.net Core中实现文件上传.请在下面查看我的结局:
I am trying to implement a file upload in Asp.net Core. See my endpoit below:
[HttpPost("upload")]
[AllowAnonymous]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
return Ok(new { count = files.Count, size, filePath });
}
当我使用Postman测试它时,即使选择任何文件,我也会得到以下结果:
When I test it using Postman I get the following result even if I select any file:
{
"count": 0,
"size": 0,
"filePath": "/var/folders/24/rmgj9ypj37709tnhxr2hgtfr0000gn/T/tmpX0SwbF.tmp"
}
推荐答案
这应该指导您正确的方向.该方法正在接收jQuery post对象.
This should guide you in the right direction. The method is receiving a jQuery post object.
[HttpPost]
public async Task<IActionResult> ReadFileHeaders(IFormFile file)
{
if (file != null)
{
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
// Now the file is loaded into the stream variable
}
}
return BadRequest("File required");
}
这篇关于如何在ASP.NET Core Web API中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!