【问题标题】:How to display/store and retrieve image as varbinary(MAX) using ASP.NET MVC view如何使用 ASP.NET MVC 视图将图像显示/存储和检索为 varbinary(MAX)
【发布时间】:2016-05-08 19:40:23
【问题描述】:

我是 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 实现上述目标吗?如果是:如何?有没有可用的建议或参考链接?

【问题讨论】:

  • 我认为你需要把这个问题分解成更小更容易识别的问题。您应该发布具有单个问题和可以重现该问题的最少代码的问题。 stackoverflow.com/help/how-to-ask

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


【解决方案1】:

首先为 Image 类创建一个视图模型

   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(image) 使用 Update(image)

【讨论】:

  • @Amin,答案不言自明。你让我的生活更轻松了。向你致敬。非常感谢。
  • @IsmailKhan 很高兴为您提供帮助,实际上这是我在 mvc 中创建注册向导表单的方法的一部分,具有更多的进步,如果您正在做这样的事情,link 可能会有所帮助跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
  • 2011-01-05
相关资源
最近更新 更多