c# - 如何在asp.net core web api中上传文件

标签 c# asp.net asp.net-core

我正在尝试在 Asp.net Core 中实现文件上传。请参阅下面的端点:

    [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 测试它时,即使我选择任何文件,我也会得到以下结果:

{
   "count": 0,
   "size": 0,
   "filePath": "/var/folders/24/rmgj9ypj37709tnhxr2hgtfr0000gn/T/tmpX0SwbF.tmp"
}

最佳答案

这应该会引导您朝着正确的方向前进。该方法正在接收一个 jQuery post 对象。

    [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");
    }

关于c# - 如何在asp.net core web api中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131710/

相关文章:

c# - 在应用程序中设置数据库的模式名称

c# uint 到 ushort 溢出,就像在 native C 中一样

c# - Azure Function 正常运行一段时间后无法加载程序集

c# - 在 Asp.Net Core Identity 中创建没有 UserManager 的用户

c# - 报告查看器打印?

asp.net - 如何使用 C# asp.net 从远程 URL 保存图像?

c# - Properties.Settings 在 ASP.NET Core 中不可用

c# - 在派生类中将属性设置为只读

c# - 从我的模型类创建 Kendo 图 TableView

c# - 在 MVC 上使用嵌套模型 3 : How to update a table inside a table?(外键)