Search My Warehouse

2009-10-26

upload and retrieve images,doc,docx,txt to and from database C#

create table imgupl(id int identity(1,1),filename varchar(500),uploadedfile image)

----------------------------------------

upload
--------

string fileName = System.IO.Path.GetFileName(this.FileUpload1.FileName);

byte[] fileContent = this.FileUpload1.FileBytes;

con.open();
using (SqlCommand command = new SqlCommand("insert into imgupl values(@Filename,@FileContent)", con))
{
SqlParameter fileNameParameter = new SqlParameter("@Filename", System.Data.SqlDbType.NVarChar, 255);
fileNameParameter.Value = fileName ;
SqlParameter fileContentParameter = new SqlParameter("@FileContent", System.Data.SqlDbType.Image);
fileContentParameter.Value = fileContent ;
command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
command.ExecuteNonQuery();
MyTemp = "Record Saved Successfully.";
}


----------------------------------------

download:
-------------
string fileId = "1";

using (SqlCommand command = new SqlCommand("SELECT filename ,uploadedfile FROM imgupl WHERE id = @FileId", connection))
{
command.Parameters.AddWithValue("@FileId", fileId.Replace("-", "||"));
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
byte[] content = reader["uploadedfile "] as byte[];
string filename = reader["filename "].ToString();
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Content-Length", content.Length.ToString());
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}
}





----------------------------------------

No comments:

Feed