I have explained how to store and retrieve image file in SQL Server in my previous post. I received many comments mentioning that how can we store and retrieve doc or pdf or excel (or any type of file) in SQL Server. Few friends (developers) have also posted comment that they receive only 13 byte when they retrieve stored image or doc or xls or pdf or rtf file. So I thought let be write another blog for them. Sorry friends I am bit late in writing this article and mean while you also have solved your issues. However this may help some new friends.
In this example I have used a table which has four fields. Below is the script for table,
CREATE TABLE [TestTable]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[FileName] [nvarchar](15) NOT NULL,
[Extension] [nvarchar](5) NOT NULL,
[Content] [image] NULL
)
Fig – (1) Scrpit for Table
In my demo project I have used one file Upload control (to upload the file), one Textbox (where user can enter ID for uploaded file to retrieve it) and 2 buttons (one for uploading file and other for retrieving).
When user select the file and click on Upload button the code stores the selected file in database. Below is the code for that,
using (SqlConnection cnn = new SqlConnection(“Connection String”))
{
cnn.Open();
SqlCommand cmd = new SqlCommand(“InsertFile”, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(“@FileName”, “Name of
Uploaded File”));
cmd.Parameters.Add(new SqlParameter(“@Extension”, “Extension of
Uploaded File”));
cmd.Parameters.Add(new SqlParameter(“@Content”, “byte array
(byte[]) of uploaded file”));
cnn.Close()
}
Fig – (2) Code for inserting selected file in database.
Now when user enter FileID for uploaded file in textbox and click on retrieve button we will get the Content and extension field from database for that file id. You can use FillDataSet method to retrieve the byte array. Below code shows how to send retrieved file to user depending on the extension.
string strExtenstion = “extension of retrieved file”;
byte[] bytFile = “Byte array retrieved from database”;
Response.Clear();
Response.Buffer = true;
if (strExtenstion == “.doc” || strExtenstion == “.docx”)
{
Response.ContentType = “application/vnd.ms-word”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.doc”);
}
else if (strExtenstion == “.xls” || strExtenstion == “.xlsx”)
{
Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.xls”);
}
else if (strExtenstion == “.pdf”)
{
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.pdf”);
}
Response.Charset = “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// If you write,
// Response.Write(bytFile1);
// then you will get only 13 byte in bytFile.
Response.BinaryWrite(bytFile);
Response.End();
Fig – (3) Code to retrieve the file from database.
Happy Programming !!!
what will the field data type of the sqltable for storing file contents
Mahender,
You can use Image or varbinary as data type.
fsfsdfsdfsdfsdfsdf
dsfsdfsdfsfsd
What is the max file size(pdf) which can save into the sql server?
Jason,
This is depend on data type that you have used to store PDF file. If you are using SQL Server 2005 and varbinary(max) as datatype than file size must be less than or equal to 2 raise to 31 bytes which is maximum limit for varbinary type. Below is the link where you can find data types and limits for SQL Server.
http://www.teratrax.com/sql_guide/data_types/sql_server_data_types.html
Hope this will help you.
ya bcp des java script http://www.vala.c.la
Hi…every body.
This is Balaji,
I am developing one application using HTML,JSP,SQL server wth Tomcat5.0 server.
In this i have to upload files to the data base.
i got one issue when trying to upload a file to the database.
Ex:
Sql database contains table “upload” with 2 fields as
(upn number(6),upf BLOB)
*********************************attach.html******************************
Attach
Upload No:
***********************upload_attach.jsp**********************************
File Uploaded Successfull
File Does not Uploaded
when i try to upload a file to the above table, its showing error message that “null”
Please can any one help me to solve this….
Thanks
Balaji
Balaji,
Can you please paste your JSP code so that I can have better idea.
Hi ,
I am developing a website with asp.net 2.0 in that i have to upload pdf file to sql database but i am not able to do so …i use your eg..above but could not succedd.
plz tell me in detail .i made the table in sql as well front end in asp.net i am able to store type of file ,name of file but not content how can i ,
how can i add byte[] array of uploaded file i am stuck at this point
cmd.Parameters.Add(new SqlParameter(“@Content”, “byte array
(byte[]) of uploaded file”));
Plz explain in detail i am in great need…
Vijay,
Look at following code. I have used file upoad control “objFileUpload” to get the file from client. objHttpPostedFile is my variable which is used to get uploaded file. Then I have created a byte array “Byte[] bytImage” with size equals to length of posted file. In last line I have read the content of file in byte array.
HttpPostedFile objHttpPostedFile = objFileUpload.PostedFile;
int intContentlength = objHttpPostedFile.ContentLength;
Byte[] bytImage =new Byte[intContentlength];
objHttpPostedFile.InputStream.Read(bytImage, 0,
intContentlength);
I hope you are able to understand upto this. Now you have to add this byte array in SQL Server. Below is the code,
cmd.Parameters.Add(new SqlParameter(“@Content”, bytImage));
In above line I have added this byte array (bytImage) in SQL parameter. You can use this parameter in stored procedure you have created.
I hope now you will able to understand the code. Let me know if you need more help.
Hello,
I have few questions regarding storing the files:-
1) Is there any other method than storing the fiels in database? If yes which is faster and more reliable.
2) What if dont want to have restriction on the size of the documents to be uploaded?
3) If I am using SQL Server/ MY sql then what is the maximum files or number of records that I can maintain? I mean I know that I can as much data, but want to know which will be faster as data keeps growing?
thanks
hi
can i get the code in vb.net to store images,pdf,mdb,xml in sql server 2005 database
plz…
Sonal,
Try these translators…. from c# to vb.net
http://authors.aspalliance.com/aldotnet/examples/translate.aspx
Thanks
John Patrick
Hi,
Thanx for ur reply,quite useful but i am stuck as i want to upload multiple files in a single attempt.
I do have a folder and i want to upload complete folder in single attempt by selecting foldername only bt fileupload control accept only single file at a time ..how can i
Hi chiragrdarji,
Here i am sending the entire code…for sql table, html page, and jsp page
i am not sure whether this method of uploading file to database is correct or not.
It very urgent for me…
my email id is: balaji@qsgsoft.com
Please send me code for this if u can..
***********Sql Table*********
create table task(tid number(6), attachment BLOB);
***************Select_Upload.html*************
Select-Upload
Task ID:
Attachment:
****************FileUpload.jsp*****************
File Upload Page
thanx in advance,
Balaji
Hi chiragrdarji
When I retrieve the Excel file from the database, I just wanna show tthe file, so the browser should be closed.
Here is part of the code how I did it.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileId"] != null)
{
int fileId = InputUtils.ScrubInt(Request.QueryString["FileId"]);
ExperimentManager manager = new ExperimentManager();
Byte[] bytes = manager.RetrieveExcelFile(fileId);
if (bytes != null)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Tr.xls”);
Response.Charset = “”;
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
}
}
how do I close the browser?
please tell me……
how can i retrive the doc, pdf etc… file from sql server
and how to show these file.. in c#.net window application 2.0
sql server- 2005
Hi Chiragrdarji,
I can save different types of documents to the database and I can retrieve the data for the documents fine.
My problem is trying to display the word or excel documents.
I get the file download dialog with Open, Save and Cancel buttons. If I click Save, the file is saved and opened just fine but when I click the Open button I get an error saying that the file could not be found. It looks like word and excel are looking for the file in a temporary directory.
I hope you can help me. Below is an excerpt of the code.
Thanks!
Dim bFileData() As Byte = ds.Tables(“FileInfo”).Rows(0)(“FileContents”)
Response.Clear()
Response.Buffer = True
If strExt = “doc” Then
Response.ContentType = “Application/vnd.ms-word”
Response.AddHeader(“content-disposition”, “attachment;filename=Tr.doc”)
ElseIf strExt = “xls” Then
Response.ContentType = “application/ms-excel”
Response.AddHeader(“content-disposition”, “attachment;filename=Tr.xls”)
Else
If strExt = “.pdf” Then
Response.ContentType = “application/pdf”
Response.AddHeader(“content-disposition”, “attachment;filename=Tr.pdf”)
End If
End If
Response.Charset = “”
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(bFileData)
Response.End()
hi iplz help me want to store & retrieve image from sql server using asp.net web application.
While uploading need to display image in image control & aslo while retrieving image has to display in image control….
Rply me soon very urgent sen_sm_art@yahoo.co.in
private void upload_Click(object sender, System.EventArgs e)
{
Stream img_strm = upload_file.PostedFile.InputStream;
//Retrieving the length of the file to upload
int img_len = upload_file.PostedFile.ContentLength;
//retrieving the type of the file to upload
string strtype= upload_file.PostedFile.ContentType.ToString();
string strname = txtimgname.Text.ToString();
byte[] imgdata = new byte[img_len];
int n = img_strm.Read(imgdata, 0, img_len);
int result = SaveToDB(strname, imgdata, strtype);
}
private int SaveToDB(string imgname, byte[] imgbin, string imgcontenttype)
{
SqlCommand command=new SqlCommand (“insert into myimages(imgname,imgfile,imgtype) values (@img_name,@img_file,@img_type)”,connection);
SqlParameter param0=new SqlParameter (“@img_name”,SqlDbType.VarChar ,30);
param0.Value =imgname;
command.Parameters .Add (param0);
SqlParameter param1=new SqlParameter (“@img_file”,SqlDbType.Image);
param1.Value =imgbin;
command.Parameters .Add (param1);
SqlParameter param2=new SqlParameter (“@img_type”,SqlDbType.VarChar ,30);
param2.Value =imgcontenttype;
command.Parameters .Add (param2);
connection.Open();
int num=command.ExecuteNonQuery ();
connection.Close ();
return num;
}
private void ViewImage_Click(object sender, System.EventArgs e)
{
connection.Open();
SqlCommand command1 = new SqlCommand(“select imgfile from myimages where imgname=@param”, connection);
SqlParameter myparam = command1.Parameters.Add(“@param”, SqlDbType.NVarChar, 30);
myparam.Value = txtimgname.Text;
byte[] img = (byte[])command1.ExecuteScalar();
MemoryStream str = new MemoryStream();
str.Write(img, 0, img.Length);
Bitmap bit = new Bitmap(str);
Response.ContentType = “image/jpeg”;//or you can select your imagetype from database or directly write it here
bit.Save(Response.OutputStream, ImageFormat.Jpeg); connection.Close();
}
Reply me soon its very urgent…………..
Senthil,
Do you have any issue during savin or retrieving image? OR you need solution about how to display image ?
hi
i like you are post …keep on posting it
Hi,
I want to store resume file in the sql server database and i need to display this file content(string format) in textbox..then i can update that file in the text area..
I can able to store file in the database..I am not able retrieve file content into the textbox..my problem is converting binary format to string format..if you know any idea..please share with me..
Regards
Balu Munugoti,India
Equinox Techs
Hi There!,
Great post!
Thanks for taking the time to put this up!
I’m developing a Window Form application in VB.net for a local health service and hope to use the code you have provided to save the pdf files.
Was wondering if you knew a way of pre-viewing the pdf file without having to open Adobe?
Thanks,
Dave
Dave Gilmore,
Yes you can preview the PDF in browser using tag available in HTML. Let me know if you need exact code.
Hi Chiragrdarji,
Thanks for your reply…
Could you provide me with a code sample?
Or point me in the right directions?
I’m building a Windows forms application so will this still work?
I was also wanting to print the pdf direct from my application.
Thanks,
Dave
I need code sample to store and retrieve doc or pdf or excel (or any type of file) in SQL Server for Windows Application using C#
How would I best save a pdf file to a SQL 2005 database in the following scenario?
I have a Web app in .Net 2.0 written in VB using VS2005. The client prints their contract to the screen in a Browser window (Recommend IE7). I give them the option to cancel (Close the window) print to their local printer or save. When it saves, I want to save the file to their customer record in my SQL 2005 DB.
I guess I am asking for an automatic “upload”. I want them to be able to save it directly to the database as opposed to saving it to file system then uploading separately.
Any and all help appreciated.
Thank you for all of your blog info!
Steve
Hello,
We are using ASP.NET and SQL Server 2005 for storing doc/jpeg/gif images in database. All thing works fine in IE and FF. But when try to open the doc file on safari browser on any platform it ask as to save the .aspx file.
How cam I open the doc file on safari browser??
Thanks,
Deepesh Verma
Deepesh,
Can you please send me your code so that I can look in to that? One more thing have you installed safari on windows or do you have MAC machine?
Hello Chirag,
I have even tried the code with is described in this article. It is also not working for me on safari. I have tried this on safari on windows and even tested it on MAC machine by the third party tool
http://www.browsercam.com
On safari it saves the aspx file and when we open it, it shows the byte array and the .aspx code is below that.
waiting for reply..
Thanks,
Deepesh Verma
Hello Chirag,
for more information, you can visit the link,
http://forums.asp.net/p/1185698/2023459.aspx
Thanks,
Deepesh
hi,
hey i wanted to add few file from any location to a specific folder
Ex. i’v few files say a.xml, b.exe ,c….
now i wanted them to be copied in a folder say X !
using C# would be fine
please suggest or forward links related to it
thanks
Akshaya
hi
i am devlepoing an application in which report is generated in HTML format Now I want to send that report in pdf file to the client,which non editable.
I am using asp.net 2.0 with vb and oracle as back end in this application.
If possible for you than please send the desire code at my mail id: nigam_tarun2003@yahoo.co.in
Tarun,
This article shows how to store and retrieve PDF file in database. To generate new PDF in Dot Net you have to use some third party software available in market. I have done using ABC PDF. Here is the artile for that
http://chiragrdarji.wordpress.com/2007/04/19/create-pdf-in-aspnet-2/
If you know any other way to generate PDF without using any thord party app, pls let me know.
I want to delete excel file through SQL Server 2000.Is it possible or not ,plz guide me for it.
hi chirag,
I am currently working on a jobsite project.when a jobseeker uploads his resume itshould be stored in the database.the resume should either be a.doc or a txt file.When the user wants to edit his profile i want that his resume should be opened and displayed to him.and if the resume clicks on the editresume link then it should be opened in a word for him to save and upload it.plz help.
Hi, how make this using ASP 3.0?
Yula,
Sorry to say that but I am not familiar with ASP.
how to store a word file in a msaccess database
and we have to brouse the file and can modify the file
and again store that fille from database to particular
path required
This code is in ASP.Net and run very well:
.
.
byte[] bytesPDF = new byte[0];
// Receive bytes from PDF (web service methods)
bytesPDF = consulta.ConsultarMovimentacaoRelatorio(codigoAgencia, numeroContrato, dataRelatorio, pagina.paginaRelatorio, pagina.identificadorProcessamento);
string nomeArquivo = “COB”+dataRelatorio.ToString()+”P”+pagina.paginaRelatorio.Replace(“/”,”DE”)+”_”+pagina.DescricaoIdentificadorProcessamento+”.pdf”;
nomeArquivo = nomeArquivo.ToUpper();
Response.Clear();
// Browser receive PDFo PDF
Response.ContentType = “application/pdf”;
Response.AddHeader(“Content-Disposition”,”attachment; filename=\”" + nomeArquivo + “\”;”);
Response.AddHeader(“‘Content-Length”,bytesPDF.Length.ToString());
// Send bytes to client browser (the browser open window pop-up for ask save or open the PDF).
Response.BinaryWrite(bytesPDF);
Response.End();
.
.
.
How can I convert this code to ASP 3.0? Anybody know???
Thanks!!!
I need code sample to store and retrieve doc or pdf or excel (or any type of file) in msaccess Server for Windows Application using C#
Thanks for the article. I do however have one issue. When I read an Excel file back from sql into an asp page I’m not getting a prompt. Just garbage on the page. Works fine for Word and PDFs but not Excel. I’m using sql 2000 image format and VS 2005 to develope the page.
Any help will be appreciated.
Hi,
Thanks for the article. In addition to the above article… I have a requirement like….need to download all the resume/doc files from a database based on the keyword for ex. i want to download all the resumes who are having 5+ yr experience.
Any help.
Thanks
Prashanth
Hiii frinds,
I m chetan singh.I created one program(C#+ASP.NET 2005, Sqlserver 2000) in which i am fatching the data from database and filling to excel sheet.
wat m i doing .
1. i m saving one excel templete in my application folder
2. fatching the data from datasource
3 creating the excel obj and the opening the excel template which r in application path
4 filling the excel sheet.
problem:
With code this is working fine.but in IIS after deploy this application its showing “Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005. ”
but i solved that error using http://blog.crowe.co.nz/archive/2006/03/02/589.aspx
after this Excel sheet is not visible. I m not able to find out wat is the error.bez excel report is not visible.
Please help me…..
Code:
oExcelApp = new Application();
oExcelApp.Visible = false;
oBooks = oExcelApp.Workbooks;
oMissing = System.Reflection.Missing.Value;
string path = Server.MapPath(“.\\Report\\IndexReport.xlt”);
oBook = oBooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
oSheet = (Excel._Worksheet)oBook.Worksheets["Market Capitalization"];
oSheet.Visible = Excel.XlSheetVisibility.xlSheetVisible;
@Chetan
oExcelApp.Visible = false;
Change this to true
Hi friends,
I have a problem in retrieving the file with exention .eml (outlook express document). Give me a sample code.
Karl Ferman
u said
******
“I can save different types of documents to the database and I can retrieve the data for the documents fine.
My problem is trying to display the word or excel documents.
I get the file download dialog with Open, Save and Cancel buttons. If I click Save, the file is saved and opened just fine but when I click the Open button I get an error saying that the file could not be found. It looks like word and excel are looking for the file in a temporary directory.
I hope you can help me. Below is an excerpt of the code.
Thanks!”
*****
to click the open button and get your file opened
u need to put
Response.Cache.SetCacheability(HttpCacheability.Private)
not
Response.Cache.SetCacheability(HttpCacheability.NoCache)
thanks for the information, I would like to know if you could help me in a situation that I have I want to be able to upload a .doc or .pdf file and then before sbmitting the documents I want to be able to display it on a text area, another question that I have I do need apppend four files contnt into just one file and then be able to create a single file with all that information and stored on the database.
thanks again!!!
Hello Every one
For Give me if this post deeshart belog in this.
What Im trying to accomplish
1) Insert an image into a Database table column of BLOB type
2) retrive that image and display it with in a web browser for vewier
Language known
1) JSP, Servlet ,Java
Database & Servers
Tomcat 5.0 & Oracle
My process is an
1) Html page with form fields for selection(upload/retrive) the image(doc/xls/ect what ever it file) from the local computer , from action is set to upload.jsp and retrive.jsp
hit submit the file will be upload in to database/retrive from the database
Hi chiragrdarji,
I am also storing files in my database. I have taken image field to store the files. But when i run my application it works fine for local system. After publishing my site when i try’s to upload the file, it shows Access Denied to that particular file. What is the possible reason i m not getting.
I am using ASP.NET 2.0 with SQL SERVER 2005. Local and Online database is one.
Need the solution urgently.
Regards
Ashok Kothari
Hi,
I m getting the following error
Error: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.
when i tried to write excel file from c# in vs2005.
Wt can be its remeady?
http://scdlpapers.blogspot.com
Hi chiragrdarji,
how to read data from Excel sheet and storing it in database thruogh programming. Please help me to Complete my Task.
Regard’s
Saleem.
Is the Tr.pdf is to be hardcoded.
Iam passing the pdf filename dynamically from the sql server query.But when i try to download the pdf file iam getting the message as ” either not a supported file type or the file has been damaged “. Iam storing the pdf file in the sql server as type ” image”
Prakash,
Can you pls send me the code so that I can have a better idea?
Saleem,
Sorry for delay. I will forward you the code in this weekend.
i have created the sql databse with two fields
1. code number
2.attach document
in my asp.net program ,i displayed these in DataGrid or view coding.i displayed the attach document as hyper link ,when i click that it will not open.please help me to how to retreive the content.
I’m in the process of trying to convert this to using an Oracle Database and not having much luck. Can you (or anyone) help? Also, do you have a demo project for this I could download?
I am downloading doc file stored in SQL server 2000 using ASP.NET. it is working fine if download accelerator is not installed.
Is there any solution please let me know.
Pavel
I am downloading doc file stored in SQL server 2000 using ASP.NET. it is working fine if download accelerator is not installed. If DA is installed it is downloading whole aspx page/.exe file.
Is there any solution please let me know.
Pavel
Hai chiragrdarji,
I have to parse a pdf file using C# in VS.Net windows application. In the pdf file tables are also present.
I need to search a particular word(city) in the pdf file and then i have to retrieve the datas which is in a single line in table format, related to that word(climate details here). Then the collected details are added to database.
Can u tell me how to do this?
Regards,
Anitha.
Can u write the separate code to retrieve the word doc from sql database and to display the contents of word file on to windows form.
Plz to that……..I am strugling a lot of problem wioth this
hello ,
i am darshak shah i have problem to access a data from access database i am using JSP technoloy plz reply me i want to access the result in a table view then what i have to do plz send me the jsp(access)coding for that..
plz it’s urgent………i need it to complete my project….
Hye Sunil
Thanks
Yes I can write the file in server disk and can open the file in windows. But If I want to download from client and if Download Accelerator Plus is in the client then pageName.aspx is downloading.
Pavel
Darshak,
Sorry yar, I am not good at JSP. I can’t help you.
Using the code above for downloading doc file from database, I am getting problem while download Accelerator Plus installed on client pc. Can any one help me pls?
Polash
Polash,
I am really sorry. I do not have solution for this. If I will find it I wil put it here. If you find it than pls post it here.
But i using WInForm, you can help me? Write and read MS Word file form SQL. Thanks!
hoe i read excel file usin java code and save record sin mysql
Sir, I want to store my images from datagrid to local disk I am using Asp.Net C# and sql server 2000 plz solve my problem sir
thanks
ramakant
Thank you very much boss..!! i don’t know who you guys are. But you really helped me ending a day long fight with search engines to find a way out to store/retrieve files in database. Thanks again…keep doing the good work….Thanks a lot guys…
Hello sir..
I do have two problems..
1. i want to extract only file name without extension .
for eg.. if i have vijay.aspx then i only want to extract vijay from this . in c#.net
2.
how can i add column in mysql database from c#.net.
i want to add column with filename extracted above.
Please do this favour as more thingsare depend on this ….
Thanx
Regards
Vijay
i would like save varbinary(max) column image file from sqlserver 2005 to a file at local server.i mean i want to save binary data as a file at local server. thank in advance. please let me know
thanks a lot
Hi chiragrdarji,
Good article, solved some of my doubts. Plz tell me how to do PDF automations in C# (2003)? Suppose I have save a PDF file of some 6 to 10 pages into SQL Server Binary field, later I will retrive them, delete any one page or add a new page and save it back. I may retrive them in Adobe Standard to do this, but how to link Adobe standard with my C# application? Please guide me how to do these kind of automations?
_
Regards,
Rajeev, B.lore.
Hello ,
I want to use resume upload facility..
i can store resume in particular folder..
But i dont know from where did u get FILE ID ????
MY CODE IS GIVEN BELOW :
Sub Upload_Picture_File(ByVal Src As Object, ByVal Args As EventArgs)
Dim savePath As String
savePath = “C:\Inetpub\wwwroot\test\images”
If Not UploadFile.HasFile Then
‘– Missing file selection
Message.Text = “Please choose a file to upload”
Else
If InStr(UCase(UploadFile.FileName), “.DOC”) = 0 Then
‘– Selection of non-JPG file
Message.Text = “You can upload only .doc files”
Else
‘If UploadFile.PostedFile.ContentLength > 100000 Then
‘ ‘– File too large
‘ Message.Text = “Uploaded file size must be less than 100 KB”
‘– File upload
Dim fileName As String = UploadFile.FileName
’savePath += fileName
savePath = Server.MapPath(“~/images/” + fileName)
UploadFile.SaveAs(savePath)
Message.Text = “File Uploaded”
Message.Text &= “File Name: ” & UploadFile.FileName & “”
End If
End If
End Sub
what changes should i do to retrieve resume ?…I am using vb language in asp.net
i am receiving an error specified cast is not valid
Dim img As Byte() = CType(cmd.ExecuteScalar(), Byte())
i want to retrieve an image stored in sql server 2000 and make it display in an image control when the form loads… how could i do that…> help me…
Thanks in advance
This is quite usedful. I used it and its working fine except for pdf which on opening giving error as an error occured file cannot be found. Can you help me.
Guys,
Does anyone know what’s the datatype for the “file” in the database.
In other words, when I am creating my table, what should I put the datatype for the field in which I want to store my file?
Hi all,
Sorry if it is wrong place 2 ask.
I’m trying to upload and retrieve doc file from MySQL database using java.
if i upload .txt file and retrieve it as .doc file, it works
but when i try upload .doc file, it was uploaded successfully. but when i try to retrieve it, it shows all garbage characters.
Thanks for any help.
Hi Friends,
Give me a valuable suggestion.
I want to save doc file in my server system at the same time i want to retrieve the file using some constraints.
I am using C# Asp.Net with Sql Server 2000.
Thanks Advance.
Saravanan,
Do you want to store doc file in database or on file system? On which constraint you want to retrieve the file? If you store it in database then it will be stored in binary field and you can not use like or full text search to compare the content of file.
If you want to store it on file system you have to assign proper rights to the folder where you are storing doc files.
Can you tell me more detail about your requirement?
How can I show & update Data of the Word document which i have stored in the Database in byte format into some control (like OLE in VB6) in the Windows Form
Can U have some idea regarding this
that any control can let me display the file data & update it
hai friends,
i want to check if any data present in the file upload control..i checked using the below specified code
If upload_file.PostedFile Is Nothing Then
but it does not accept empty string….it always going to its else part
Pls help me.
Mehender,
How can I open a file like you did from sqlserver but I want to open it in a new browser window withour writing it to a file. Is this possible?
Hi,
In my appl., i’m trying to upload the file in DB, this is happening.
Could u tell me how retrieve from DB to open in the browser through downloading.
Thank & Regards
Chandru
hi
I’m trying to open the file from the byte[] which is stored in the database. I’m doing this successfull on my machine and other machine but one machine trying to find the file into the Temporary Internet files folder and the file doesn’t get open as i’m storing the contents into the database.
So can any help me why the application is behaving in such a manner
Regards
Gaurav
hi
How to open a pdf or jpeg file in I E 6.0
Regards
Gaurav
hi
i had a big doubt
can any 1 give me the xat answer
i ve only 200 mb sqlserver space in my server,how many doc files(sized:100kb) can be stored in the db sql server2005.
again
will it reduce the size of .doc file while storing to database
urgent help needed
Hi
First off, great article!!!
Do you have the sample code for the article? Could you share it?
Thank you in advance!
For anyone that needs the solution code….I followed this article and came to this simplified version of the solution (this is the .aspx.cs file):
using System;
using System.Collections;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void upload_Click(object sender, EventArgs e)
{
Int32 File1Length = File1Upload.PostedFile.ContentLength;
String File1Type = File1Upload.PostedFile.ContentType;
Stream File1Stream;
File1Stream = File1Upload.PostedFile.InputStream;
String File1Name = File1Upload.PostedFile.FileName;
byte[] File1Content = new byte[File1Length];
File1Stream.Read(File1Content, 0, File1Length);
SqlConnection cnn = new SqlConnection(“Data Source=SABBYPC;Initial Catalog=eodocuments;Integrated Security=True”);
SqlCommand cmd = new SqlCommand(“INSERT into dbo.TestTable (FileName,Extension,Content) VALUES (@FileName,@Extension,@Content)”);
//SqlCommand cmd = new SqlCommand(“InsertFile”, cnn);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(“@FileName”, SqlDbType.NVarChar, 100));
cmd.Parameters.Add(new SqlParameter(“@Extension”, SqlDbType.NVarChar, 50));
SqlParameter contentParameter = null;
contentParameter = new SqlParameter(“@Content”, SqlDbType.VarBinary);
contentParameter.Direction = ParameterDirection.Input;
cmd.Parameters.Add(contentParameter);
cmd.Parameters["@FileName"].Value = File1Name;
cmd.Parameters["@Extension"].Value = File1Type;
cmd.Parameters["@Content"].Value = File1Content;
cnn.Open();
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
cnn.Close();
}
protected void retrieve_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(“Data Source=SABBYPC;Initial Catalog=eodocuments;Integrated Security=True”);
SqlCommand cmd = new SqlCommand(“SELECT Content,Extension FROM dbo.TestTable WHERE ID=2″/* + ImageIdentity*/, conn);
conn.Open();
//start reading
SqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Reader.Read();
Response.Clear();
/// Read the database content into a byte array
byte[] reportFile = (byte[])Reader["Content"];
Response.ContentType = Reader["Extension"].ToString();
Response.Buffer = true;
Response.Charset = “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(reportFile);
Response.End();
conn.Close();
}
}
hi every body,
this is harika working for a software company.
I have a bug regarding retrieving the file which stored in database.
In my application, I need to save and retrieve the files. All the files are saving properly in a binary format, but coming to retrieving when i am trying to retrieve i’m getting the whole file as “system.Byte[]“. And wen iam trying to open it from gridview it is showing only “System.Byte[]“.
Will you please any one know the solution reply it.
Thanks in advance….
Harika.M
You can retrieve the file with HyperlinkFiled:
this (downloadFile.aspx) should call the page in my earlier reply to retrieve the appropriate file.
You can retrieve the file with HyperlinkFiled:
–> <–
this (downloadFile.aspx) should call the page in my earlier reply to retrieve the appropriate file.
jhgh
hi chirag plz tell me how to update,insert,edit in grid view in asp.net.plz it’s urgent.
Hai,
I Designed a Adobe Form using Adobe LiveCycle Designer with 2 fields and Submit button…the Fields are Name and Designation.
When the User Enter the values into a Adobe From the Values will posted or Redirected to the .Aspx Page and Saved into the SqlServer when the user Clicks a Submit Button.
Plz Help me………………..
Thamks.
Used it for 2 of my apps.
I am sure others find this useful.
Bookmarked it: http://www.codebounce.com/ASPNET
Cognitive page!, man
Hi
This is a very nice example for ASP.NET Apps. Does anybody have an example how to realize the same functionality in a WinForm App? I want to show a pdf file in a WinForm App that is loaded from a binary field in SQL Server 2005 or 2008. I’m already looking for a long time and didn’t find a solution so far even not a commercial product.
I appreciate any help.
Greez stefan
Superb articles for every one.
it seems that you and all your friends in the picture above have bandages. What happened? Well sorry in advance.
Hi,
Can you advise how to change the maximum file size for storing .doc, .pdf etc in a SQL Server 2005 database. At the moment we use nvarchar but thi comes with a 4MB file size limit.
We’d like to extend this- any help would be appreciated.
Thanks.
reading from xls to write into sql using c#.net pls tell me
how to show preview of .doc file in a textbox in my aspx page
i hav a fileupload control at top of my page and i have a upload button and textbox with multiline mode
by using uploadcontrol i can browse a doc file and clik on upload button
with this clik i want to show tet of that doc file uploaded in a textbox which is in center of page
Is there any way to store .pdf. .doc, jpeg, gif file to SQL database and agian retain it to same format. I mean upload and down load above mentioned files
I need document attachment functionality in windows application.
Hi Chiragrdarji,
Love to read your posts.
Yu are great…
Here i found a dead end. which is ofcourse related to this blog.
RETRIEVING IMAGE FROM SQL SERVER 2000 to DATALIST in ASP.NET 2005
When iam doing this retrieving .. through both “dataset” (code behind)
and “DataList1″(binding with SqlDataSource control) differently but not in the same page.
What iam gettting in the Image control which i have in DATALIST is this…String.Byte[] instead of image.
I even tried like this also:
<asp:Label ID=”emp_picLabel” runat=”server” Text=”>
still i can see …String.Byte[] in my image control which is in DataList1.
How can i bind the image to my Datalist as iam displaying emplyees details with their pictures which are been stored in sql server 2000.
How can i catch that string bytes (image file) from sql serve r and conver that into image and bind that to image control of DATALIST..Pls suggest
Thanks in advance.
<asp:Label ID=”empr_picLabel” runat=”server” Text=”>
Dear sir,
i want,how to stored and retrieved the file from sql server 2000 in C#.net windows application..very urjent sir.plse reply how to stored and retrieved windows application.Is it possible then how to do it?plse help me…
With regards
Sathis kumar.A
Dear sir,
i want,how to stored and retrieved the file from sql server 2000 in C#.net windows application..very urjent sir.plse reply how to stored and retrieved windows application.Is it possible then how to do it?plse help me…plse contact my mail id
vgp_sathis@yahoo.com
With regards
Sathis kumar.A
Friends,
I want to retrieve the filename from database and display it in the file upload control.Is it possible?
abcdefghijklmnopqrstuvwxyz;,.
Dear friends,
consider if we have controls in a web form(aspx) that web form also contains a user control(ascx) in it, How to validate that user control (.ascx), which is in that (aspx)web form along other controls. pls help me.
Thanks & Regards
Jsingh
My problem is while trying to display the excel,PDF documents.
I get the file download dialog with Open, Save and Cancel buttons. If I click Save, the file is saved and opened just fine but when I click the Open button I get an error saying that the file could not be found. It looks like word and excel are looking for the file in a temporary directory.
I hope you can help me. Below is an excerpt of the code.
Thanks!
Please find the code
string strExtenstion = “.xls”;
byte[] bytFile = lobjReportBC.GetDocument();
Response.Clear();
Response.Buffer = true;
if (strExtenstion == “.doc” || strExtenstion == “.docx”)
{
Response.ContentType = “application/vnd.ms-word”;
Response.AddHeader(“content-disposition”,
“attachment;filename=Upload.doc”);
}
else if (strExtenstion == “.xls” || strExtenstion == “.xlsx”)
{
Response.ContentType = “Application/x-msexcel”;
Response.AddHeader(“content-disposition”,
“attachment;filename=DBUSER.xls”);
}
else if (strExtenstion == “.pdf”)
{
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”,
“attachment;filename=slow_aging_process.pdf”);
}
Response.Charset = “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytFile);
// Response.End();
thank you so much!
i’v used the code for uploading and retrieving image files from SQL server in an asp page…….
using (SqlConnection cnn = new SqlConnection(“Connection String”))
{
cnn.Open();
SqlCommand cmd = new SqlCommand(“InsertFile”, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(“@FileName”, “Name of Uploaded File”));
cmd.Parameters.Add(new SqlParameter(“@Extension”,”Extension of Uploaded File”));
cmd.Parameters.Add(new SqlParameter(“@Content”, “byte array(byte[]) of uploaded file”));
cnn.Close();
}
kindly mail me the code of the stored procedure named InsertFile used in the above code….
Hi I have the following code for retrieving the data from database and it is working fine in IE6. But in case of IE7 it blinks the new window and disappears. and on some system it gives the error while opening a file “The file is damaged. And could not be open.” for IE6 also. Please give me the solutions..
————————————————————————–
SqlCommand cmd2 = new SqlCommand(“select Commentary_PDFContent from PdfCommentary where Commentary_ID=’” + comID + “‘”, Conn);
object ob = cmd2.ExecuteScalar();
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, ob);
Byte[] bytRetrv = ms.ToArray();
Response.Clear();
Response.Buffer = true;
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”, “attachment;filename=Commentary.pdf”);
Response.Charset = “”;
Response.BinaryWrite(bytRetrv);
Response.Flush();
Response.End();
Conn.Close();
return true;
Hello Chirag,
Very helpful post but I was hoping to get some more infomation to resolve my issue.
For our application I have implemented the upload feature but I am having issues in viewing the documents created using Excel 2007. I get an error saying “Excel found unreadable content in .xls. Do you want to recover the contents of this workbook?” and when I click Yes I get another a warning saying “Damage to the file was so extensive that repairs were not possible.Excel attempted to recover your formulas and values, but some data may have been lost or correupted.” and when I click Yes I am able to see the content of the file but all the formatting like the colors or font formats are lost.
Interestingly uploading and viewing workbooks saved in 2003 version work without any problem.
We are using SQL 2005 as DB. We are saving the document data in varbinary format set to max.
I tried to dig into some of the solutions available online, most of which talk about “Current Time Member” and to modify KPI settings. I have no idea what they exactly are. Any help in regard would be appreciated.
Thanks,
Sara
I am sorry I would like to correct my previous post. I just noticed that I am using Excel 2003 and not Excel 2007. What made me think that earlier is because if I save the excel file in the Microsoft Excel 97 – Excel 2003 & 5.0/95 Workbook, it saves a retrives fine but saving the file in the dafault format ‘Microsoft Office Excel Workbook’ returns the error.
Thanks for your help.
Sara
Hi I am looking for C# code for uploading word documents or Pdf documents to the Sql server db and retrieve them to the Datagrid as hyperlink and also should be able to save the document or open the document. Please assist.
Urgent help required.
I am using:
VS 2005
.net 2.0
sql server 2005
Thanks in advance…
Hi, i am trying to retrieve the ms accesss data in c# web method.
By using the oledbcommand and reader all that, i have tried doing that. However, it doesnt show the reslts.
is there any solution ?
Hi ChiraG,
I am getting an error
“File does not start with %PDF-”
I tried searching it online, but did not find any answer to it.
Can you please elaborate on it.
My code is exactly as u wrote here.
hi sir
when i use that code.Error is generated like this:-
String or binary data would be truncated.
The statement has been terminated.
i am using in data base nvarcha datatype.or image.
please solve it.
thanks
chitranjan
How To Retrieve and Display Records from an sql server 2000 Database by Using ASP.NET with c# coding………..
can any ne help me……..please…………..my mail address is gurufrnds_maharaj@yahoo.com
Hi,
How can i specify the Response.ContentType using code behind for different file types like .jpg,.doc etc…… i hv a column in DB which stores the extension of the file while uploading.
Can u please help me in this. Thanks in advance.
hi guys,,
i need help for retrieving BinaryData from Sqlserver 2005
Hello,
i want to retrieve loop through Binary Data from sqlserver and download that in MS Word doc file.
Please help me out.
thanks
hi,
what u want
HI Chirag,
i want,how to stored and retrieved the rich text data from sql server 2000 image data type in jsp page..very urjent .plz reply how to stored and retrieved data of rich text editor Is it possible then how to do it?plse help me…plse contact my mail id
kavithakunduru@gmail.com
With regards
Kavitha.K
I am trying to convert your code to VB and I am having a lot of problems. Can you help with the conversion ot VB?
i need java code for storing a data from web to sql
regards,
manju
i tried the above coding i got the following error.
Operand type clash: nvarchar is incompatible with image
can anyone help me….its urgent
hi,
i have developed the application in asp.net to upload the files(doc/txt/jpeg…..) in database, and it runs successfully now i want to open a file directly into it’s specific application when i insert a name of it into a textbox and click on open.
please reply………
thanx in advance
Hi,
How to store and retrieve. Xls,. Doc,. PDF,. jpg ,.bmp file into sql server 2005 using C# windows Application.
Could u please help me …
Thanks
Kumar
just add this code to the new .aspx page and popup this page on button click (using java script)
Dim ds As RSTIL.Purchase_OrderDataSet
ds = CType(HttpContext.Current.Session(“DataSetPurchase_Order”), DataSet)
Dim annexture_id As Integer
annexture_id = Request.QueryString(“annexture_id”)
‘filtering record- annexture_id from datatable..
Dim drfound() As DataRow = ds.ERP_Trn_Purchase_Order_Annextures.Select(“Order_Annexture_ID=” & annexture_id.ToString)
If drfound.Length > 0 Then
Response.Clear()
Dim filename As String
filename = drfound(0)(“Annexture_Doc_Name”).ToString
Response.Buffer = True
Response.Charset = “”
Response.AppendHeader(“content-disposition”, “attachment; filename=” + filename)
Response.OutputStream.Write(CType(drfound(0)(“Annexture_Doc”), Byte()), 0, CType(drfound(0)(“Annexture_Doc”), Byte()).Length)
Response.OutputStream.Flush()
Response.OutputStream.Close()
ClientScript.RegisterStartupScript(GetType(Boolean), “aa”, ” windowclose() “)
regards,
ANKIT CHAMPANERIYA
(SURAT)
Please send me the project
thanks
hi….. dude………
can u share the whole application with me…… plzzz email me this whole application … thanks
waiting for ur response…
hi
i’ve been able to save a .pdf file into the database, but i’m unable to retrieve it… at the point of opening the pdf file, adobe acrobat reader says the file is corrupt…what can i do about this? also i need to retrieve the same file using php as well…need help urgently…
thanks a lot
also, should i try zipping before saving the file?
Hi,
I am doing my project with asp.net as front end & sql server 2005 as backend. c#is my code behind.
I need to store the files in database and have to retrieve them. I tried with the coding mentioned above. But its not working for me. The file itself is not getting stored. I need the coding in detail. with stored procedure. Please either reply to this post or mail me to mail id .. I need ti urgently to finish my project
madhumitha65@gmail.com
HI
I am developing a project in which MS Access 2007 is the backend and C# 2.0 is front end. How can I save and retrieve files in MS Access 2007.
Help Urgently required.
Thanks
Karuna
hi.i am a developer in asp.net with c#.
i have a problem .
i want to submit .doc file in sql server 2005.
plz help me
plz send me code this mail
mohit.chauhan8@gmail.com
HI
I am developing a project in which MS Access 2007 is the backend and C# 2.0 is front end.It is a windows application. How can I save and retrieve files in MS Access 2007.
Help Urgently required. Pls send me code through this mail
karunagoyal@gmail.com
Thanks
Karuna
i am developing a project in which sql server database and C# 2.0 It is a web application.
my (pdf/text) file is inserting a database but when i m retrive a (pdf/text) file from the database .and open
does’t open
plz urgent help me any person .thank you in advance
(mohit.chauhan8@gmail.com)
Can i have the complete code of this. If any one have please mail me to dora.meka@gmail.com.
[...] file you have to use TEXT data type… Check the following… How to store PDFs in SQL SERVER 2000 Storing and Retrieving doc/pdf/xls files in SQL Server Tech Treasure __________________ MohammedU SQL Server [...]
Retrieving and stoing database is working but how to open the retrived file in a new window
Very helpful article.
Does anyone know how to open, read and extract a HTML file content (that stored in my local C driver) using Javascript and C# from another web application?
I don’t want to use window.open(), but I tried xmlhttp.open (‘GET’, ‘my.html’) or document.open() and used getElementsTagName or getElementsByID and I could not extract the html content at all. I kept getting invalid object and access deny error messages. It’s very frustrated.
Any help would be appreciated it. Thanks.
Dhussan
hi chiragrdarji
Retrieving and storing database is working but how to open the retrived file in a new word window
regards
Prince chacko
Hi Guys,
Very useful post, can you suggest me how to chunk very big pdf file in chuncks of 2mb and store database table ?
hi…..may get the full code for retrieve file (.doc,.docx,.ppt,.pptx,.gif,.psd.cdr,.pdf,.publisher)
or can u give me full code for retrieve .doc
Hi
Can i get the exe to upload and retrive a pdf file from SQL server.
Its very urgent
how can i retrive the doc, pdf etc… file from sql server
and how to show these file.. in c#.net window application 2.0
sql server- 200
how can i retrive the doc, pdf etc… file from sql server
and how to show these file.. in c#.net window application 2.0
sql server- 2000
pls help me
can you give me the full code for store and retrieve the file in sql 2000 in asp.net using vb.net coding
how to add the flash animation in asp.net
pls help me
how to retrieve the files in sql 2000 in word format