0

I am really new to this but I was learning how to store an image in a SQL Server database. All seems good, however the image as it's been stored can't be viewed in the database. I would like to know it there is a way I can store and view in the database itself?

My code stores the image correctly, but I want to be able to click on it in SQL Server and display image:

FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;

if (img.HasFile && img.PostedFile != null)
{
    // To create a PostedFile
    HttpPostedFile File = imgUpload.PostedFile;

    // Create byte Array with file len
    imgByte = new Byte[File.ContentLength];

    // Force the control to load data in array
    File.InputStream.Read(imgByte, 0, File.ContentLength);
}

string query = "insert into dbo.sell_trans (photo ) values (@eimg)";
SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.AddWithValue("@eimg", imgByte);

cmd.ExecuteNonQuery();
conn.Close();

Output:

ss

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Abcode
  • 25
  • 1
  • 7
  • 3
    You want to view it in SSMS? Not sure there's any built in functionality for that. It should be relatively easy to create an app that reads the record and displays the image however. Probably less than 50 lines of code. – mason Mar 24 '20 at 15:50

2 Answers2

1

There's no direct way that I know of that would allow you to view your image directly from the database, after its just stored as a binary blob and the.

An alternative would be to store the image outside of the database and then enter the image URL into the database field.

Or as mentioned by @mason you could write simple app to display the image for your.

ChrisBD
  • 9,104
  • 3
  • 22
  • 35
  • as i am saving people record i wanted just go to database and click to view. Anyways thank you. – Abcode Mar 24 '20 at 16:25
-1

You can store these images as Base64, it will be easier for you to see them as all browers can render a base64 image, you just have to copy the generated hash and paste into your address bar and the image will show up, you can even put a base64 hash inside a tag like this <img src="base64Hash" /> and this will work. But saving images and other files inside the database is not a good practice since the table size can grow really fast as the uploads occurs.

My recomendation is store these files in a directory inside your server or use a storage service like Amazon S3 or Azure Blobs, than you get its path and save it on your database column.

But in any case if you still want to use this approach, I'm pasting an stackoverflow question that shows how to get a base64 from a file and reverse it back

Converting file into Base64String and back again

Andre.Santarosa
  • 1,150
  • 1
  • 9
  • 22
  • thank you i will try that way. I thought there is a way to save as test.jpg and just click and view straight. – Abcode Mar 24 '20 at 16:25