如何使用ASP.NET MVC视图显示/存储和检索图像为varbinary(MAX)

时间:2016-05-08 19:40:23

标签: sql-server asp.net-mvc datatable asp.net-mvc-viewmodel varbinarymax

我是ASP.NET MVC的新手,也是错误的借口。

我需要一个视图页面(index.cshtml),我可以在其中显示图像,通过将图像存储在SQL Server表的Varbinary(max)列中来更改/删除图像。

数据库表中有以下列:

ID int  primary key Identity not null,
ImageName  nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null

我使用Image.cs代码:

public class Image
{
    public int ID {get; set;}
    public string ImageName {get; set;}
    public byte[] ImagePicInBytes {get; set;}
}

ImageContext课程如下

public class ImageContext : DbContext
{
    public DbSet<Image> Images { get; set; }
}

连接字符串如下

<connectionStrings>
    <add name="ImageContext"  
         connectionString="server=.; database=Sample; integrated security =SSPI" 
         providerName="System.Data.SqlClient"/>
</connectionStrings>

ImageController如下

public class ImageController : Controller
{
    private ImageContext db = new ImageContext();

    // GET: /Image/
    public ActionResult Index()
    {
        return View(db.Images.ToList());
    }

    // GET: /Image/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Image image = db.Images.Find(id);

        if (image == null)
        {
            return HttpNotFound();
        }

        return View(image);
    }
}

创建了如下视图

public class ImageController : Controller
{

        private ImageContext db = new ImageContext();

        // GET: /Image/
        public ActionResult Index()
        {
            return View(db.Images.ToList());
        }


        // GET: /Image/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        // GET: /Image/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Image image = db.Images.Find(id);
            if (image == null)
            {
                return HttpNotFound();
            }
            return View(image);
        }

        // POST: /Image/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Image image = db.Images.Find(id);
            db.Images.Remove(image);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}

我的create.cshtml(查看)如下

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ImageName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ImagePicInBytes)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ImageName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ImagePicInBytes)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

我有以下3个问题

  1. 如何通过将新图像从文件系统上传到数据库中的Varbinary列来在数据表中创建新记录?

  2. 如何让视图在“创建视图”和“编辑视图”中拥有FILEUPLOAD控件

  3. 我可以使用HttpPostedFileBaseCreate.cshtml实现上述目标吗?如果是的话:怎么样?有任何建议或参考链接吗?

1 个答案:

答案 0 :(得分:3)

首先为Image类

创建一个viewmodel
   public class ImageViewModel
   {
    public string ImageName {get; set;}
    public HttpPostedFileBase ImagePic {get; set;}
   }

然后在创建视图中上传照片

@model ExmpleProject.Models.ImageViewModel

@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})){ 

         @Html.AntiForgeryToken() 
         @Html.LabelFor(m => m.ImageName)
         @Html.TextBoxFor(m => m.ImageName)

         @Html.LabelFor(m => m.ImagePic )
         @Html.TextBoxFor(m => m.ImagePic , new { type = "file" })
         <br />
         <input type="submit" name="Submit" id="Submit" value="Upload" />
    }

然后在你的控制器的post方法中创建

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
    if (ModelState.IsValid)
    {
       var uploadedFile = (model.ImagePic != null && model.ImagePic.ContentLength > 0) ? new byte[model.ImagePic.InputStream.Length] : null;
                if (uploadedFile != null)
                {
                    model.ImagePic.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
                }
        Image image = new Image
        {
            ImageName = model.ImageName,
            ImagePicInBytes = uploadedFile
        }
        db.Create(image);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(model);
}

因此,对于您的编辑方法,您可以执行类似的实现,但不使用Create(图像),而是使用Update(image)