我想使用Entity Framework将图像(从文件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"]
我只得到了null。然后,我使用了这段代码,但是我的图像只能得到124个字节。相反inpStream.Length
我使用了Request.TotalBytes
和Request.ContentLength
,但结果相同。请帮我!先感谢您。
祝你好运, alenan13