我是 ASP.Net MVC 的新手,正在处理数据库中的图像列。我的问题是如何从控制器检索图像路径并发送到 HttpPostedFileBase 图像模型?我在我的代码中收到错误,告诉我Image = row.Image
无法将类型“字符串”隐式转换为“system.web.httppostedfilebase”
这是我的代码:
控制器
public ActionResult CategoryForm(int? Id, int CategoryGroupId)
{
if (Id != null)
{
model = (from row in db.Categories
where row.Id == Id
select new NewCategoryViewModel
{
Id = row.Id,
CategoryGroupId = CategoryGroupId,
Name = row.Name,
Description = row.Description,
Image = row.Image,
Status = row.Status,
isMain = row.isMain
}).Single();
}
return PartialView("_CategoryFormPartialView", model);
}
模型
public class NewCategoryViewModel
{
public int Id { get; set; }
public int CategoryGroupId { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public HttpPostedFileBase Image { get; set; }
[Required]
public bool Status { get; set; }
[Required]
[Display (Name = "Display as main category?")]
public bool isMain { get; set; }
}
谢谢你帮助我。
首先,我强烈建议您不要将图像存储在您的数据库中。这是非常低效的,你的数据库的性能会急剧下降。我的建议是将图像上传到服务器并将参考保存在您的数据库中。这是我必须将图像上传到保存在日期结构文件夹 [YYYY/MM/DD] 中的服务器的类的链接。
此外,如果数据库返回的是字符串而不是字节数组,则可能您正在保存文件名而不是文件。我建议阅读这篇文章只是为了确认您正在保存文件。
来自数据库的图像不是 HttpPostedFileBase 类型。您需要转换文件。
如果您使用 SQL Server 的图像字段,则需要使用字节数组并将图像转换为 MemoryStream。
模型:
public byte[] Image { get; set; }
控制器:
Image = ConvertToImage(row.Image),
private HttpPostedFileBase ConvertToImage(byte[] image)
{
System.IO.File.ReadAllBytes(image);
return(HttpPostedFileBase)new MemoryPostedFile(bytes);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句