sql-server – 如何将图像插入sql server数据库?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何将图像插入sql server数据库?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如上所述,我正在尝试在表中插入图像,其中字段的类型是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);
    }

但是当我试图上传图像时(点击“创建”按钮),我有以下内容

entry is not a valid base64 string because it contains a character
that is not base 64

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

谢谢 !

编辑:

感谢收到的答案,似乎很适合插入.但是为了显示,我仍然有问题(仅显示“未找到的图像”piture).我尝试过两种方式:
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();
    }    
}

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

解决方法

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,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,(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 })" />

猜你在找的MsSQL相关文章