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

Asp.net mvc 4 如何在asp.net中将图像文件转换为二进制文件,asp.net-mvc-4,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 有一些无效的参数 您的代码很好,但我只会使用此类型任务

我正在控制器内编写此代码

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 有一些无效的参数


您的代码很好,但我只会使用此类型任务的快捷方式:

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

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

我甚至试过这个,但文件上仍然有错误。它说System.Web.Mvc.Controller.File是一种在给定上下文中无效的方法。来自参数的更多文件名也是空的。我用代码段更新了答案,该代码段将文件发布到服务器,并从定位文件中获取字节。希望这会有所帮助。您能显示读取文件的整个控制器操作吗?[HttpPost]公共字节[]新报告字符串文件名{FileStream fs=new FileStreamfileName,FileMode.Open,FileAccess.Read;BinaryReader br=new BinaryReaderfs;byte[]image=br.ReadBytesintfs.Length;}我甚至尝试将参数类型从string转换为HttpPostedFileBase,但还是出现了相同的错误。它还说传入的文件是空的…你确定这是真的吗?它包含两个错误:fileName和fileName-不同的变量,不返回任何值。如果您想按名称返回报告,我认为应该使用HostingEnvironment.MapPath~/folderwithfiles+filename。HttpPostedFileBase-用于在服务器上发布文件,但操作的目的是什么?只返回已发布的文件?不,我想将其保存在sql server数据库中
<configuration>
    <system.web>
        <!--here I extend max length to 200Mb-->
        <httpRuntime maxRequestLength="204800" />
    </system.web>
</configuration>