【发布时间】:2016-04-19 13:06:02
【问题描述】:
我知道这不是一个新问题,但我查看了所有相关主题,但找不到我的答案。 我的问题是我已将图像数据存储到 sql db 中,但无法在编辑或索引(MVC 5)上显示它们。你能帮帮我吗,在此先感谢。 这是我的代码:
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "DrvId,FullName,Address,Postcode,Contact,Email,County,File,Date")] DriverReg driverReg, HttpPostedFileBase[] files)
{
if (ModelState.IsValid)
{
try
{
/*Lopp for multiple files*/
foreach (HttpPostedFileBase file in files)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Content/UploadedFiles/" + filename));
string filepathtosave = "UploadedFiles/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
ViewBag.Message = "File Uploaded successfully.";
}
catch
{
ViewBag.Message = "Error while uploading the files.";
}
db.DriversReg.Add(driverReg);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(driverReg);
}
型号
namespace HopeRemovalsFinal.Models
{
public class DriverReg
{
[Key]
public int DrvId { get; set; }
public string FullName { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string County { get; set; }
[DataType(DataType.Upload)]
[Display(Name ="Upload File")]
[Required(ErrorMessage ="Please choose file to upload")]
public string File { get; set; }
// public string FileName { get; set; }
public DateTime Date { get; set; }
}
public class DriverDbContext : DbContext
{
public DriverDbContext()
: base("VanRemovals")
{
}
public static DriverDbContext Create()
{
return new DriverDbContext();
}
public DbSet<DriverReg> DriversReg { get; set; }
}
}
详情查看
<dt>
@Html.DisplayNameFor(model => model.File)
</dt>
<dd>
@Html.DisplayFor(model => model.File)
</dd>
数据库结果
Create New
FullName Address Postcode Contact Email County Upload File Date
John manchester M32 7DD 098764587 john@hotm.com Lancashire uk_map.png 19/04/2016 00:00:00 Edit | Details | Delete
UploadedFiles 文件夹 为空,但文件已保存在 db 中。 感谢您的帮助。
【问题讨论】:
-
当您说“数据库上的文件数据”和“文件已保存”时,您是在说文件本身被保存到数据库吗?或者您是否将文件系统上的位置作为字符串保存到该字段“文件”
-
大家好,是的,文件已保存在数据库中,但无法在详细信息视图中显示
-
确定吗?还是只保存了名字??
-
另外,从您显示的代码中,我们从未看到您在传入的 DriverReg 对象上分配了 File 字段。
-
foreach(文件中的 HttpPostedFileBase 文件):文件可能为空
标签: c# asp.net asp.net-mvc razor asp.net-mvc-5