database - 为什么不能以这种方式将图像保存到数据库?

标签 database asp.net-mvc asp.net-mvc-3 sql-server-2008 image-uploading

我想将图像和一些其他信息保存到我的 asp.net mc3 项目中的数据库中。我之前已经将图像保存到数据库并且它有效。我在 Controller 中的代码是这样的:

public ActionResult savetodb()
{
    if (Request.Files.Count > 0 && Request.Files[0] != null)
        {
             HttpPostedFileBase file = Request.Files[0];
             var path = Path.Combine(Server.MapPath("~/Content/Image"), file.FileName); 
             file.SaveAs(path);
             byte[] buffer = System.IO.File.ReadAllBytes(path);
             myAd.AdImage = buffer;
             StoreDb.AddToAds(myAd);
             StoreDb.SaveChanges();
        }
        return View();      
    }
}

现在换了表,想把Image以外的其他信息存到数据库中。现在我的代码是这样的:

 public ActionResult savetodb(AdvertiseView model)
 {
     if (Request.Files.Count > 0 && Request.Files[0] != null)
     {
         HttpPostedFileBase file = Request.Files[0];
         var path = Path.Combine(Server.MapPath("~/Content/Image"), file.FileName);
         file.SaveAs(path);
         byte[] buffer = System.IO.File.ReadAllBytes(path);
         myAd.AdImage = buffer;
     }
     myAd.AdTitle = model.AdTitle;
     myAd.AdContext = model.context;
     myAd.AdScope = model.Scope;
     storedb.AddToAds(myAd);
     storedb.SaveChanges();
     return View();
}

其他信息没有问题,就是图片无法保存。我明白了

Request.Files.Count

return 0,不知道现在该怎么办。有人可以帮我吗?多谢。

最佳答案

我会使用 View 模型。

假设您首先有一个领域模型:

public class MyDomainModel
{
    public byte[] AdImage { get; set; }
    public string Description { get; set; }
}

然后定义一个 View 模型:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }

    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
}

Controller :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // TODO: move this mapping logic into a 
        // mapping layer to avoid polluting the controller
        // I would recommend AutoMapper for this purpose
        // http://automapper.org/
        using (var stream = new MemoryStream())
        {
            model.File.InputStream.CopyTo(stream);
            var image = stream.ToArray();
            var domainModel = new MyDomainModel
            {
                AdImage = image,
                Description = model.Description
            };

            // TODO: persist the domain model by passing it to a method
            // on your DAL layer
        }

        return Content("Thanks for submitting");
    }
}

一旦推荐的重构完成:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        MyDomainModel domainModel = Mapper.Map<MyViewModel, MyDomainModel>(model);

        // TODO: persist the domain model by passing it to a method
        // on your DAL layer

        return Content("Thanks for submitting");
    }
}

最后是允许用户上传文件的 View :

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.Description)
        @Html.EditorFor(x => x.Description)
    </div>

    <div>
        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)
    </div>    
    <button type="submit">OK</button>
}

关于database - 为什么不能以这种方式将图像保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970992/

相关文章:

database - 天蝎座隐藏显示情绪

.net - 如何强制硬刷新 (ctrl+F5)?

asp.net-mvc - 请求被中止 : Could not create SSL/TLS secure channel. System.Net.WebException

asp.net-mvc-3 - 可空 bool 值的复选框

mysql - 传输mysql Access 包括关系和外键?

mysql - 在 Joomla 中更新数据库的多行和多列

jquery - 选择最后动态添加的文本框

c# - 从方法调用两个 Web 服务而不相互阻塞的最佳方法

c# - DisplayFor 不适用于具有不同命名空间的相同模型名称

mysql - 无法识别的关键字 Near Fields,在 mysql 查询中使用 INTO OUTFILE 时终止