考虑以下代码片段:
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不再支持,似乎有替代方案。我正在寻找它,请指导我
HttpPostedFileBase
已替换为 IFormFile
中的 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
}
该方法的签名必须更改,因为 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();
}
}