ASP.NET Core MVC 中的输入流

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

考虑以下代码片段:

public ActionResult Upload(HttpPostedFileBase file)
{
        byte[] buffer= new byte[256];
        file.InputStream.Read(buffer, 0, 256);
        //...
}

InputStream
命令在 ASP.NET Core MVC 中不起作用。

☝asp.net mvc core中的inputstream不再支持,似乎有替代方案。我正在寻找它,请指导我

c# asp.net-core asp.net-core-mvc
2个回答
11
投票

HttpPostedFileBase
已替换为
IFormFile
中的
ASP.NET Core

请参阅有关 ASP.NET Core 中文件上传

的文档

您的控制器操作方法应该接受一个

IFormFile
实例。

public ActionResult Upload (IFormFile file)

IFormFile
提供以下方法来访问其
Stream

public interface IFormFile
{
    Stream OpenReadStream();

    void CopyTo(Stream target);

    Task CopyToAsync(Stream target, CancellationToken cancellationToken = default);

    // Remaining members
}

2
投票

该方法的签名必须更改,因为 NetCore 不支持

HttpPostedFileBase
。相反,引入了 IFormFile。

你的方法签名应该是这样的

public ActionResult Upload (IFormFile file)

要解决这个问题,您可以使用如下所示的辅助功能来帮助自己:

public ActionResult Upload (IFormFile file)
{
    byte[] buffer= new byte[file.Length];
    var resultInBytes= ConvertToBytes(file);
    Array.Copy(resultInBytes,buffer,resultInBytes.Length);

    return Ok(buffer);

}

private byte[] ConvertToBytes(IFormFile image)
{
   using (var memoryStream = new MemoryStream())
   {
     image.OpenReadStream().CopyTo(memoryStream);
      return memoryStream.ToArray();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.