Asp.net mvc 4 将图像文件发送到asp.net mvc4中的控制器操作方法

Asp.net mvc 4 将图像文件发送到asp.net mvc4中的控制器操作方法,asp.net-mvc-4,Asp.net Mvc 4,我正在尝试通过从用户处获取图像来调用控制器操作方法“NewReport”。它确实调用了控制器函数,但在控制器内部,当我试图使用此文件将其转换为二进制时,它表示为null <h2>Basic File Upload</h2> @using (Html.BeginForm("NewReport", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}) { <label for="file

我正在尝试通过从用户处获取图像来调用控制器操作方法“NewReport”。它确实调用了控制器函数,但在控制器内部,当我试图使用此文件将其转换为二进制时,它表示为null

<h2>Basic File Upload</h2>

@using (Html.BeginForm("NewReport", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})
{
    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />
    <br><br>
    @ViewBag.Message
}
基本文件上传
@使用(Html.BeginForm(“NewReport”、“Home”、FormMethod.Post、new{enctype=“multipart/formdata”})
{
上载图像:




@查看包。留言 }
您的操作方法不正确,发布给您的不是文件名,而是实际的字节内容。请尝试以下操作:

public ActionResult NewReport(HttpPostedFileBase file)
{
    // Do something with the file here
    var fileName = file.FileName;
    var fileContentStream = file.InputStream;

    //Store the file on your webserver
    file.SaveAs(string.Format(@"c:\somefolder\{0}", file.FileName);

    return View();
}

也请发布控制器操作方法。[HttpPost]公共字节[]新报告(字符串文件名){FileStream fs=new FileStream(文件名,FileMode.Open,FileAccess.Read);BinaryReader br=new BinaryReader(fs);byte[]image=br.ReadBytes((int)fs.Length);}但它不会像在你的情况下保存在c中的文件夹一样保存在我的电脑中。我希望它保存在sql server数据库中名为ImageContent的表列中。实际上,我要做的是首先调用action方法。在该action方法中,我会将文件转换为字节内容或二进制,然后保存到sql server数据库中。@user3532152我的代码将其保存到驱动器,您不必这样做。从
文件中获取字节流。InputStream
并将数据从那里插入到您的数据库中。@user3532152如果您需要帮助,请打开另一个问题。这个问题只是为了将文件转换为操作方法。非常感谢。图像正在保存在我的driv中E