且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将一个图像插入SQL Server数据库?

更新时间:2023-10-15 09:33:34

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