3

如前所述,我正在尝试在表中插入图像,其中字段的类型是 Varbinary。

到目前为止我做了什么:

我有一个包含许多字段的表单:

@using (Html.BeginForm("InsertProduct", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>PRODUCT</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.PRODUCT_ID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PRODUCT_ID)
            @Html.ValidationMessageFor(model => model.PRODUCT_ID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PRODUCT_NAME)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PRODUCT_NAME)
            @Html.ValidationMessageFor(model => model.PRODUCT_NAME)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.PRODUCT_IMAGE)
        </div>
        <div class="editor-field">
            <input type="file" name="PRODUCT_IMAGE" id="PRODUCT_IMAGE" style="width: 100%;" />
        </div>

        <p>
            <input type="submit" value="Create" class="btn btn-primary"/>
        </p>
    </fieldset>
}

所有这些字段都允许我在我的控制器中构造一个 PRODUCT 对象:

public ActionResult InsertProduct(PRODUCT ord)
    {
        MigrationEntities1 sent = new MigrationEntities1();
        sent.PRODUCT.Add(ord);
        sent.SaveChanges();
        List<PRODUCT> Products = sent.PRODUCT.ToList();
        return View("Products", Products);
    }

但是当我尝试上传图像(通过单击创建按钮)时,我有以下内容:

条目不是有效的 base64 字符串,因为它包含不是 base 64 的字符

所以首先:这是处理图像的正确方法,其次,我认为我需要对我的图像进行预处理以插入它:如何处理?

谢谢 !


编辑 :

感谢收到的答案,似乎有利于插入。但是对于显示,我仍然有问题(仅显示“未找到图像”图)。我尝试了两种方法:1 <img src="LoadImage?id=@Model.product.PRODUCT_ID"/> .在控制器中

public Image LoadImage(int id)
    {
        String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
        DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
        PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();

        MemoryStream ms = new MemoryStream(product.PRODUCT_IMAGE);
        Image img = Image.FromStream(ms);
        return img;
    }

和 2. :

@{

    if (Model.product.PRODUCT_IMAGE != null)
    {
        WebImage wi = new WebImage(Model.product.PRODUCT_IMAGE);
        wi.Resize(700, 700,true, true);
        wi.Write();
    }    
}

但他们都没有工作。我究竟做错了什么 ?

4

3 回答 3

4

1)改变你的数据库表有这些列:

1: ProductImage - varbinary(MAX)
2: ImageMimeType - varchar(50)

2)像这样更改您的操作方法:

public ActionResult InsertProduct(PRODUCT ord, 
    HttpPostedFileBase PRODUCT_IMAGE)
{        
    if (ModelState.IsValid)        
        {
            MigrationEntities1 sent = new MigrationEntities1();
            if (image != null)
            {
                ord.ProductImage= new byte[PRODUCT_IMAGE.ContentLength];
                ord.ImageMimeType = PRODUCT_IMAGE.ContentType;
                PRODUCT_IMAGE.InputStream.Read(ord.ProductImage, 0,
                    PRODUCT_IMAGE.ContentLength);
            }

            else
            {
                // Set the default image:
                Image img = Image.FromFile(
                    Server.MapPath(Url.Content("~/Images/Icons/nopic.png")));
                MemoryStream ms = new MemoryStream();
                img.Save(ms, ImageFormat.Png); // change to other format
                ms.Seek(0, SeekOrigin.Begin);
                ord.ProductImage= new byte[ms.Length];
                ord.ImageMimeType= "image/png";
                ms.Read(ord.Pic, 0, (int)ms.Length);
            }

            try
            {
                sent.PRODUCT.Add(ord);
                sent.SaveChanges();

                ViewBag.HasError = "0";
                ViewBag.DialogTitle = "Insert successful";
                ViewBag.DialogText = "...";
            }
            catch
            {
                ViewBag.HasError = "1";
                ViewBag.DialogTitle = "Server Error!";
                ViewBag.DialogText = "...";
            }

            List<PRODUCT> Products = sent.PRODUCT.ToList();
            return View("Products", Products);
        }

        return View(ord);
    }

此操作方法仅用于创建。您也需要一些用于编辑和索引的作品。如果您有问题,请告诉我将它们的代码添加到答案中。

更新:如何显示图像:

显示存储图像的一种方法如下:

1)将此操作方法添加到您的控制器:

    [AllowAnonymous]
    public FileContentResult GetProductPic(int id)
    {
        PRODUCT p = db.PRODUCTS.FirstOrDefault(n => n.ID == id);
        if (p != null)
        {
            return File(p.ProductImage, p.ImageMimeType);
        }

        else
        {
            return null;
        }
    }

2)在你的视图结构中(或任何你想要的地方)添加一个<img>标签,如下所示:@foreach(...)

<img width="100" height="100" src="@Url.Action("GetProductPic", "Products", routeValues: new { id = item.ID })" />
于 2013-07-31T12:03:47.547 回答
0

所以,这里是要做的修改:

  1. 在数据库中插入数据:

    [HttpPost]

    public ActionResult InsertProduct(PRODUCT ord, HttpPostedFileBase image) { MigrationEntities1 sent = new MigrationEntities1(); if (image != null) { ord.PRODUCT_IMAGE = new byte[image.ContentLength]; image.InputStream.Read(ord.PRODUCT_IMAGE, 0, image.ContentLength); } send.PRODUCT.Add(ord); 已发送.SaveChanges(); 列出产品 = sent.PRODUCT.ToList(); 返回视图(“产品”,产品);}

注意:这是“轻”的方式,对于更完整的内容,请查看 Amin 的答案。

  1. 用于显示:

在视图中

<img src="LoadImage?id=@Model.product.PRODUCT_ID"/>

在控制器中:

public FileContentResult LoadImage(int id)
    {
        String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
        DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
        PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();

        return new FileContentResult(product.PRODUCT_IMAGE, "image/jpeg");
    }

现在一切正常,谢谢!

于 2013-07-31T12:48:35.647 回答
0

将 sql 服务器上的 Image 类型更改为 Byte[] 并使用类似的东西。这就是我过去存储图像的方式。

http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv

如果没有,您始终可以将图像存储在本地,并通过字符串将图像位置传递到 SQL 数据库中,这种方法效果很好,并且可以快速设置。

于 2013-07-31T09:29:55.817 回答