如何在asp.net中将图像文件转换为二进制文件

时间:2014-05-24 21:54:38

标签: asp.net-mvc-4

我在控制器

中编写此代码
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);

我收到此错误

  

最佳重载方法匹配或System.IO.FileStream.FileStream   有一些无效的论点。

1 个答案:

答案 0 :(得分:0)

你的代码很好,但我只使用这种任务的快捷方式:

byte[] image = File.ReadAllBytes(fileName);

编辑: 如果你想在文件中发布文件,然后将其保存在db中 - 最简单的方法是用文章发布它:

<form action="@Url.Action("NewReport")" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

然后你的行动应该是这样的:

[HttpPost]
public ActionResult NewReport(HttpPostedFileBase file)
{
    byte[] image = new byte[file.ContentLength];
    file.InputStream.Read(image, 0, image.Length);
    //here the code that saves image to db and returns action result
}

请注意,asp.net中发布文件的最大长度为4Mb,但您可以在web.config文件中轻松扩展到适合您的大小:

<configuration>
    <system.web>
        <!--here I extend max length to 200Mb-->
        <httpRuntime maxRequestLength="204800" />
    </system.web>
</configuration>