使用Entity Framework将图像存储到数据库

时间:2013-11-09 12:59:08

标签: asp.net-mvc image entity-framework

我想使用Entity Framework将图像(从文件pngjpg)保存到数据库。

我的代码在这里:

    [HttpPost]
    public ActionResult Create(Food fd)
    {
        try
        {
            FoodOrderEntities fo = new FoodOrderEntities();              


            Stream inpStream = Request.InputStream;
            Int32 length = Convert.ToInt32(inpStream.Length);

            byte[] tempImage = new byte[length];
            inpStream.Read(tempImage, 0, length);               

            //FoodImage  is an image field in the datatable, mapped by the Entity Framework
            fd.FoodImage = tempImage;                

            fo.AddToFood(fd);
            fo.SaveChanges();

            return RedirectToAction("Index");
          }
        catch
        {
            return View();
        }
    }

我的观点是:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <h2>Create</h2>
    <% using (Html.BeginForm("Create","Food",FormMethod.Post,new {enctype="multipart/form-data"})) {%>
    <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.FoodName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.FoodName) %>
            <%: Html.ValidationMessageFor(model => model.FoodName) %>
        </div>          

        <div>
            Select a file: <input type="file" name="fileUpload" />
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

  <% } %>

   <div>
       <%: Html.ActionLink("Back to List", "Index") %>
   </div>
</asp:Content>

但是,使用Request.Files["fileUpload"]我只得到了null。然后,我使用了这段代码,但是我的图像只能得到124个字节。相反inpStream.Length我使用了Request.TotalBytesRequest.ContentLength,但结果相同。请帮我!先感谢您。

祝你好运, alenan13

0 个答案:

没有答案