Professional Documents
Culture Documents
DatabaseView
our advertisersAdvertise with us
ASP.NET, All Topics, C#, .NET >> C# Database >> General
Uploading / Downloading Pictures to / from a SQL Server
By Alexandru Ghiondea
Describes how to upload and download pictures to and from a
SQL Server database. C#, SQL
Windows (WinXP), .NET (.NET 1.1)
Win32, SQL (SQL 2000), VS (VS.NET2003)
DB, Dev
Posted 29 Oct 2004 4:49
Articles by this author
18,413 views
Search: Articles Authors
Help!ArticlesMessage BoardsStoreFrontLounge
Toolbox
Broken Article?
VS.NET 2003 for $899
Ultimate Toolbox $499
Print version
Send to a friend
Sign in / Sign up
Email
Password
Remember me
Introduction
In order to provide your application with cool pictures, you can employ
two techniques (at least). One of them is that you can save the pictures
in a folder and store the path to each one in a database or file. The
other one is to store the entire file into a database, along with its file
name.
Each of them has its ups and downs:
If you save your files to a folder, you might accidentally delete a file
from that folder. If this happens, you will end up with a broken link
in your database or configuration file. However, the hard disk storage
space is cheap, so you can afford to store a lot of files.
If you store your files into a database, you can enforce security by
using the security settings of the database. Also, there are no broken
links ever. However, the database storage space is more expensive.
Another idea is that you can save a thumbnail of the image on the database
for quick access and save the actual picture on hard drive.
Of course, each application has its particularities, and you have to
choose which one you will use.
OK. Enough of the philosophical talk! Let s dive into the good stuff.
The application
The problem of uploading files to a database is not that difficult. You
have to use, on the server, a certain data type when creating the table.
This data type has to be capable of storing large amounts of binary data.
When using Microsoft SQL Server, this data type is called image.
For more information, see BLOB (Binary Large OBject) for a short
definition, and Books Online for a complete reference.
The client has to obtain the data from the file in binary format
a byte
array
and call a procedure on the server with that array as a parameter.
The SQL Server procedures
In this presentation, I assume that I have a database Pictures on the
server with a table called Pictures. The structure of this table is as
follows:
Field NameField Type
kFileNameLong
PictureImage
FileNameVarchar(250)
I also have stored procedures for uploading, downloading, and retrieving
the list of uploaded files. These are shown below.
For uploading a file: UploadFile:
CREATE PROCEDURE [dbo].[UploadFile]
(
@Picture image,
@FileName varchar(250),
@kFileName bigint output
)
AS
insert into Pictures(Picture, FileName) values (@Picture,@FileName)
select @kFileName = SCOPE_IDENTITY()
GOFor downloading a file: DownloadFile:
CREATE PROCEDURE [dbo].[DownloadFile]
(
@kFileName bigint,
@FileName varchar(250) output
)
AS
//
// Initializes the DataAdapter used for retrieving the data
//
da = new SqlDataAdapter(cmd);
// ---------------------------------------------//
// Opens the connection and populates the dataset
//
conn.Open();
da.Fill(ds,table);
conn.Close();
// ---------------------------------------------}
catch(Exception e)
{
//
// If an error occurs, we assign null to the result
// and display the error to the user,
// with information about the StackTrace for debugging purposes.
//
Console.WriteLine(e.Message + " - " + e.StackTrace);
}
}
/// <SUMMARY>
/// Uploads a file to the database server.
/// </SUMMARY>
/// <PARAM name="fileName">The filename of the picture to be uploaded</PARAM>
/// <RETURNS>The id of the file on the server.</RETURNS>
public long UploadFile(string FileName)
{
if (!File.Exists(FileName))
{
return -1;
}
FileStream fs=null;
try
{
#region Reading file
fs = new FileStream(FileName,FileMode.Open);
//
// Finding out the size of the file to be uploaded
//
FileInfo fi = new FileInfo(FileName);
long temp = fi.Length;
int lung = Convert.ToInt32(temp);
// -----------------------------------------//
// Reading the content of the file into an array of bytes.
//
byte[] picture=new byte[lung];
fs.Read(picture,0,lung);
fs.Close();
// ------------------------------------------
#endregion
long result = uploadFileToDatabase(picture,fi.Name);
return result;
}
catch(Exception e)
{
Console.WriteLine(e.Message + " - " + e.StackTrace);
return -1;
}
}
/// <SUMMARY>
/// Wrapper for downloading a file from a database.
/// </SUMMARY>
/// <PARAM name="kFileName">The Unique ID of the file in database</PARAM>
/// <PARAM name="fileName">The file name as it was stored
///
in the database.</PARAM>
/// <RETURNS>The byte array required OR null if the ID is not found</RETURNS>
public byte[] DownloadFile(long kFileName, ref string fileName)
{
byte[] result = downloadFileFromDatabase(kFileName, ref fileName);
return result;
}
/// <SUMMARY>
/// Returns the connection string for connecting to the database
/// </SUMMARY>
/// <RETURNS>The Connection string.</RETURNS>
public static string ConnectionString()
{
//
// We consider that the database is situated
// on the same computer that runs the program.
// To connect to a remote server, replace 'Data Source'
// with the name of that server.
//
return "Connect Timeout=600;Integrated Security=SSPI;" +
"Persist Security Info=False;Initial Catalog=Pictures;" +
"Packet Size=4096;Data Source=" +
System.Environment.MachineName.Trim();
}
/// <SUMMARY>
/// Uploades a file to an SQL Server.
/// </SUMMARY>
/// <PARAM name="picture">A byte array that contains
///
the information to be uploaded.</PARAM>
/// <PARAM name="fileName">The file name asociated
///
with that byte array.</PARAM>
/// <RETURNS>The unique ID of the file on the server
///
OR -1 if an error occurs.</RETURNS>
private long uploadFileToDatabase(byte[] picture, string fileName)
{
//
// Defining the variables required for accesing the database server.
//
SqlConnection conn = null;
SqlCommand cmd =null;
SqlParameter kFileName =null;
}
else
{
msg = "An error has occured";
}
MessageBox.Show(msg);
}
private void LoadInformationFromDataBase()
{
TransferPictures up = new TransferPictures();
up.GetUploadedFiles(ref ds,"Pictures");
UploadedFiles.DataSource = ds.Tables["Pictures"];
UploadedFiles.DisplayMember = "Name";
}
private void frmMain_Load(object sender, System.EventArgs e)
{
LoadInformationFromDataBase();
}Conclusion
Well, choosing which type of image
file
storage technique to use is up
to the person designing a specific application. I have tried here to show
you how you can store them in a database. Happy coding!
Bibliography
Books Online
MSDN
About Alexandru Ghiondea
Student at the Computer Science Faculty in Bucharest
Click here to view Alexandru Ghiondea's online profile.
Other popular articles:
QueryCommander SQL Editor
QueryCommander SQL editor with IntelliSense, wrapped in a Visual
Studio type of environment. QueryCommander supports: Microsoft SQL
Server 6.5-2005, MySQL 4.*-5.1, and Oracle 9i.
SQL Injection Attacks and Some Tips on How to Prevent Them
Discusses various aspects of SQL Injection attacks, what to look
for in your code, and how to secure it against SQL Injection
attacks.
SQL Server DO's and DONT's
SQL Server database best practices
Inserting relational data using DataSet and DataAdapter
This article describes the process of inserting data in a DataSet
and then submitting this changes to the database. It targets the
issue when having IDENTITY/AutoNumber columns in the database.
[Top]Sign in to vote for this article:
PoorExcellent
Premium Sponsor
FAQ Noise level Very High High Medium Low Very low Search
comments
View Normal (slow) Preview (slow) Message View Topic View
[Reply][Email][View Thread][Get
Link][Modify|Delete]
Happy coding!
[Reply][Email][View Thread][Get
Link][Modify|Delete]
Hi!
I'm interested in storinc pictures or word
documents for an application i'm developping but
i'm not sure if this is the best way to do it. I
have been trying to store the pictures to the
server (in a folder) and store at the DB the
path of the picture.
What do you think is better to store the entire
pic to the DB or my way of storing only the
path?
Thanks!
Jordi
"Catalonia is not Spain"
[Reply][Email][View Thread][Get
Link][Modify|Delete]
Developersdex
Tek-Tips Forums