How to save image in SQL Server database?

I want to save images uploaded using httppostedfilebaseto the database.

How should I do it? How to structure database fields? What code am I writing to save it to the database?

+3
source share
4 answers

First of all, storing images in a database is a moot point, so be sure to think about whether this is really what you want. For a detailed discussion, see:

Storage of images in a DB - Yes or No?

, , - , . Linq2SQL, NHibernate, Entity Framework ADO.NET? , ( , ). , , .

HttpPostedFileBase.InputStream.

+1
if(uploadedImage == null || uploadedImage.ContentLength == 0)
{
    // no image
}

var image = new Image();
image.Name = uploadedImage.FileName;
image.ContentType = uploadedImage.ContentType;
int length = uploadedImage.ContentLength;
byte[] buffer = new byte[length];
uploadedImage.InputStream.Read(buffer, 0, length);
image.Data = buffer;

Image class - , Name, ContentType Data . uploadedImage HttpPostedFileBase.

+1
[HttpPost]
    public ActionResult SaveImage(HttpPostedFileBase image)
    {
       Foo foo=new Foo();
       if (image != null)
            {
                foo.ImageMimeType = image.ContentType;//public string ImageMimeType { get; set; }
                foo.ImageData = new byte[image.ContentLength];//public byte[] ImageData { get; set; }
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            fooRepository.Save(foo);
        }
    }
+1
source

Source: https://habr.com/ru/post/1761518/


All Articles