user1987631
user1987631

Reputation:

What is the proper way of saving an image in asp.net?

In my system, there is a feature that will save the image of the item added, What I do is I will save the filename of the image into SQL server, and the image will be save into the one of the folder of asp.net

here us my code for saving the filename of the image in sql server:

INSERT INTO schemaImage.Image(image_name) VALUES ('image1.FileName')

here is my code for saving the image into the folder:

image1.SaveAs(Server.MapPath("Images/" + image1.FileName))

is it possible to save an image into the database?

What is more proper in saving an image here?

Upvotes: 1

Views: 2348

Answers (3)

Chukwuemeka
Chukwuemeka

Reputation: 372

  1. Yes, it is possible to save an image as a binary type in SQL Server.

    Details: http://www.asp.net-crawler.com/articles/ADO.Net/Storing-binary-blob-data-images-files-SQL-server-ADONet.aspx

  2. The proper way of saving an image depends on your application's requirements: e.g If you will need to modify the pictures very often and they're large, it's more appropriate to save them in your file system as it's built to handle fragmentation better. Even more details..

Upvotes: 1

Mahmut Ali ÖZKURAN
Mahmut Ali ÖZKURAN

Reputation: 1140

Of course you can store image data in SQL Server there are data types like varbinary and image to store image data. You may find detailed information about usage of those types at this link. But all before that you MUST read Storing images in SQL Server? to decide whether to store images on database.

Upvotes: 0

ThinkingStiff
ThinkingStiff

Reputation: 65341

You need to convert the image to bytes to store it in the database. You can use IO.File.ReadAllBytes() for local files or Net.WebClient.DownloadData() for web files. The IMAGE data type is going away in SQL Server, so use VARBINARY(MAX) to store it.

Code:

Dim url As String = "http://example.com/image.png",
    file As String = "c:\image.png"

Using connection As New Data.SqlClient.SqlConnection("your connection string"),
    saveImage As New Data.SqlClient.SqlCommand("dbo.saveImage", connection)

    connection.Open()
    saveImage.CommandType = Data.CommandType.StoredProcedure

    'use only one of these
    saveImage.Parameters.AddWithValue("@imageData", New Net.WebClient().DownloadData(url)) 'get file from url
    'saveImage.Parameters.AddWithValue("@imageData", IO.File.ReadAllBytes(file)) 'get file locally

    saveImage.ExecuteNonQuery()

End Using

Procedure:

CREATE PROCEDURE [dbo].[saveImage] ( @imageData AS VARBINARY(MAX) )
AS
INSERT INTO dbo.myImage ( imageData ) VALUES ( @imageData )

Table:

CREATE TABLE [dbo].[myImage](
    [imageData] [varbinary](max) NOT NULL
) 

Upvotes: 0

Related Questions