如何将一个图像插入SQL Server数据库? [英] How to insert an image into sql server database?

查看:116
本文介绍了如何将一个图像插入SQL Server数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

至于说,我想要在一个表中,其中字段的类型是VARBINARY插入图像。

As said, i'm trying to insert an image in a table, where the type of the field is Varbinary.

是我到目前为止已经完成的:

What i've done so far :

我有一个表格许多领域:

I've a form with many fields:

@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>
}

和所有这些领域让我来构造一个产品对象在我的控制器:

And all these fields allow me to construct a PRODUCT object in my controller :

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);
    }

但是,当我试图上传的图片(点击创建按钮),我已经下列内容:

But when i'm trying to upload the image (by clicking on Create button), i've the following :

条目是​​无效的base64字符串,因为它包含了一个字符
  这不是基地64

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

所以首先:它是处理图像的正确方法;第二,我想我需要做我的图像上的pre-treatemant插入它?如何惟愿

So first of all : is it the right way to deal with images and second, I think I need to do a pre-treatemant on my image to insert it : how to o that ?

谢谢!

编辑:

由于收到的答案,似乎是很好的插入。但是显示,我仍然有问题(只显示未找到图像piture)。我已经尝试做两种方式:
1。
&LT; IMG SRC =LoadImage?id=@Model.product.PRODUCT_ID/&GT;
并在控制器

Thanks to answers received, seems to be good for insertion. But for displaying, I still have issues (only the "not found image" piture is displayed). I've try to do it two ways : 1. <img src="LoadImage?id=@Model.product.PRODUCT_ID"/> and in the controller

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();
    }    
}

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

But none of them are working. What am I doing wrong ?

推荐答案

1)更改数据库表中有这些列:

1) Change your database table to have these columns:

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

2)改变你的操作方法是这样的:

2) Change your action method like this:

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);
    }

这动作方法只是为了创造。你需要一些作品编辑和索引了。如果你有问题做他们,告诉我将它们添加的codeS答案。

This action method is just for create. you need some works for edit and index too. If you have problem to doing them, tell me to add codes of them to the answer.

更新:如何显示图片:

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

One way to show stored images is as the following:

1),该操作方法添加到您的控制器:

1) Add this action method to your controller:

    [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)添加&LT; IMG&GT; 标记中的 @foreach(...)结构中的视图(或任何你想要的)是这样的:

2) Add a <img> tag in the @foreach(...) structure of your view (or wherever you want) like this:

<img width="100" height="100" src="@Url.Action("GetProductPic", "Products", routeValues: new { id = item.ID })" />

这篇关于如何将一个图像插入SQL Server数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆