1

我想使用实体框架将图像(从文件png或)保存到数据库。jpg

我的代码在这里:

    [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"]我得到的只是空值。然后,我使用了这段代码,但我只能从我的图像中获得 124 个字节。相反,inpStream.Length我使用了Request.TotalBytesand Request.ContentLength,但结果相同。请帮我!先感谢您。

最好的问候, alenan13

4

0 回答 0