C#图片或文件转二进制流输出

在编写接口的时候,有些时候前端开发人员会要求把图片或文件以二进制流的方式进行返回,代码其实是非常简单的。

public ActionResult GetUserPic(Guid id)
{
   string path =imgurl //图片路径;
   if (System.IO.File.Exists(path)) //判断文件是否存在
   {
     // 读文件成二进制流
     using (FileStream stream = new FileStream(path, FileMode.Open))
     {
       long bufferLength = stream.Length;
       byte[] bufferFile = new byte[bufferLength];
       stream.Read(bufferFile, 0, bufferFile.Length);
       string contentType = “image/jpeg”;
       stream.Close();
       return new FileContentResult(bufferFile, contentType);
     }
   }
}

THE END