我想上传并向数据库显示图像。我有一个模型来添加EmployeeFirstName,LastName,...和员工图像。当我发布除了图像文件之外发布的所有数据。
这是我的代码。
型号:
namespace EmployeeTask.Models
{
using System;
using System.Collections.Generic;
public partial class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public Nullable<System.DateTime> HiringDate { get; set; }
public byte[] Image { get; set; }
}
}
查看:
<div id="dialogEmployeeEditor">
<div>
<h2>Add/Edit Employee</h2>
<table>
<tr>
<td><a href="javascript:EmployeeEditor_Save();">Save</a></td>
</tr>
</table>
</div>
<div id="Container">
<form id="frmEmployeeEditor">
<table border="1">
<tr>
<td>First Name</td>
<td>
<input type="text" name="FirstName" id="EmployeeEditor_FirstName" value="@emp.FirstName" />
</td>
</tr>
.........
<tr>
<td>Upload Image</td>
<td>
<input type="file" name="imageFile" id="image" />
</td>
</tr>
</table>
<input type="hidden" name="employeeId" value="@emp.Id" />
</form>
</div>
</div>
<script type="text/javascript">
function EmployeeEditor_Save() {
$.post("/Employees/SaveEmployee", $("#frmEmployeeEditor").serialize(), function (e) {
$("#EmployeesGridContainer").replaceWith($(e));
$("#PopUpContaine").dialog("close");
}, "json");
}
</script>
控制器:
[HttpPost]
public ActionResult SaveEmployee(int employeeId)
{
SaveEmployeeDate(employeeId,Request.Form);
return PartialView("_EmployeesGrid");
}
public void SaveEmployeeDate(int employeeId, NameValueCollection Data)
{
Employee emp = db.Employees.FirstOrDefault(c => c.Id == employeeId);
if (emp == null)
{
emp = db.Employees.Create();
db.Employees.Add(emp);
}
emp.FirstName = Data["FirstName"];
emp.MiddleName = Data["MiddleName"];
emp.LastName = Data["LastName"];
emp.HiringDate = Convert.ToDateTime(Data["HiringDate"]);
emp.Department = Data["Department"];
HttpPostedFileBase image = Request.Files["imageFile"];
if (image != null && image.ContentLength > 0)
{
byte[] imageBytes = new byte[image.ContentLength];
image.InputStream.Read(imageBytes, 0, image.ContentLength);
emp.Image = imageBytes;
}
db.SaveChanges();
}
答案 0 :(得分:5)
要使HttpPostedFileBase
类型正确发布,您需要在表单标题中添加enctype="multipart/form-data"
。您可以手动将其写为<form id="frmEmployeeEditor" enctype="multipart/form-data">
,但我建议使用MVC的表单助手来执行相同的操作(在您的cshtml视图中):
@using (Http.BeginForm("Employee", "SaveEmployee", FormMethod.Post, new {enctype="multipart/form-data"})
{
// Your form goes here
<input type="file" name="imageFile" id="image" />
}
然后,在你的控制器中,你只需在你的帖子动作中添加一个自动获取文件的参数,如下所示:
public ActionResult SaveEmployee(int employeeId, HttpPostedFileBase imageFile)
{
// Controller code here
}
imageFile
不应该为null,您可以将其保存到磁盘,或者将字节保存到数据库中。