Insert or Upload document into database and retrieving, downloading with Saving option using C# and asp.net


First Create a table with the name Document in database which requires to saving  and  retrieving from database.
For Save, Just am saving NameOftheDocument,Document,DocumentType and Filename.
For that Design textbox and fileupload control and one Save button using asp.net
Then  in Save button click event write the following code:
    protected void btnSave_Click(object sender, EventArgs e)
        {
            string NameOftheDocument = txtNameOfDocument.Text;
            byte[] imgbyte = new byte[0];
            string DocType = string.Empty;
            string FileName = string.Empty;
            if (AsyFUCreateDocument.HasFile)
            {
                int length = AsyFUCreateDocument.PostedFile.ContentLength;
                imgbyte = new byte[length];
                HttpPostedFile img = AsyFUCreateDocument.PostedFile;
                img.InputStream.Read(imgbyte, 0, length);
                DocType = AsyFUCreateDocument.PostedFile.ContentType;
                FileName = AsyFUCreateDocument.PostedFile.FileName;
             }

//Pass these fields are as parameters to database and Save it.

 // Create SQL Connection

            SqlConnection con = new SqlConnection("data Source=ADMIN;initial catalog=databasename; user id=Sa; password=123");
            // Create SQL Command
             SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Document(NameOftheDocument,Document,DocumentType , Filename)" + " VALUES (@NameOftheDocument,@Document,@DocumentType ,@ Filename)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            SqlParameter NameOftheDocument       new SqlParameter("@NameOftheDocument",SqlDbType.VarChar, 50);
           NameOftheDocument.Value = NameOftheDocument.ToString();
            cmd.Parameters.Add(NameOftheDocument);

           
            SqlParameter Documentnew SqlParameter("@Document ",SqlDbType.Image, imgbyte.Length);
           Document.Value = imgbyte;
            cmd.Parameters.Add(Document);
            SqlParameter DocumentType new SqlParameter("@DocumentType ",SqlDbType.VarChar, 50);
           DocumentType.Value = DocumentType.ToString();
            cmd.Parameters.Add(DocumentType);

            SqlParameter Filenamenew SqlParameter("@Filename ",SqlDbType.VarChar, 50);
           Filename.Value = Filename.ToString();
            cmd.Parameters.Add(Filename);

            con.Open();

            int result = cmd.ExecuteNonQuery();

            con.Close();

            if (result > 0)

                lbmsg.Text = "Document Uploaded";



Then retrieve data from document table by using data Adapter and fill it into dataset.


After that:


The following article is showing about download a document file form dataset table[0] means one datatable.

For that first you have to retrieve data from database and Fill it into One Datatable.
Then write the following methods where ever you requires.


public string GetMimeTypeByFileName(string sFileName)
     {
         string sMime = "application/octet-stream";

         string sExtension = System.IO.Path.GetExtension(sFileName);
         if (!string.IsNullOrEmpty(sExtension))
         {
             sExtension = sExtension.Replace(".", "");
             sExtension = sExtension.ToLower();

             if (sExtension == "xls" || sExtension == "xlsx")
             {
                 sMime = "application/ms-excel";
             }
             else if (sExtension == "doc" || sExtension == "docx")
             {
                 sMime = "application/msword";
             }
             else if (sExtension == "ppt" || sExtension == "pptx")
             {
                 sMime = "application/ms-powerpoint";
             }
             else if (sExtension == "pdf")
             {
                 sMime = "application/pdf";
             }
             else if (sExtension == "rtf")
             {
                 sMime = "application/rtf";
             }
             else if (sExtension == "zip")
             {
                 sMime = "application/zip";
             }
             else if (sExtension == "mp3")
             {
                 sMime = "audio/mpeg";
             }
             else if (sExtension == "bmp")
             {
                 sMime = "image/bmp";
             }
             else if (sExtension == "gif")
             {
                 sMime = "image/gif";
             }
             else if (sExtension == "jpg" || sExtension == "jpeg")
             {
                 sMime = "image/jpeg";
             }
             else if (sExtension == "png")
             {
                 sMime = "image/png";
             }
             else if (sExtension == "tiff" || sExtension == "tif")
             {
                 sMime = "image/tiff";
             }
             else if (sExtension == "txt")
             {
                 sMime = "text/plain";
             }
         }

         return sMime;
     }



The following DataTable dt, you can take from your dataset tables[0] then write the method and

Call the following method in Download button click:
     public void download(DataTable dt)
     {
         Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
         string filename = dt.Rows[0]["FileName"].ToString();
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.Buffer = false;
      HttpContext.Current.Response.Charset = "";
      HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
      HttpContext.Current.Response.ContentType = GetMimeTypeByFileName(filename);

      HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename="+filename.Replace(" ", "_"));
      HttpContext.Current.Response.BinaryWrite(bytes);
  
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.End();

     }

After clicking Download button then you will get Open with file and Save file Options.
    

2 comments:



  1. thanks for sharing this code vary useful http://soft-engineering.blogspot.in/

    ReplyDelete