How To: Setup Direct to Database Upload/Download

Last post 08-09-2012, 10:07 AM by Kenneth. 1 replies.
Sort Posts: Previous Next
  •  08-08-2012, 6:45 PM 74380

    How To: Setup Direct to Database Upload/Download


    This example assumes the following platform technologies
    asp.net v20 - 3.5
    C#
    Sql 2005
    IIS 6+

    AjaxUploader comes with an args.OpenStream() method that will allow you to convert your document to binary and store it directly to a Sql Table.

    Once there, you'll also need an .ashx file to help with the downloading of the file from the database from the web page.

    Your db table needs to have a column with data type varbinary(max)

    You also need to set up a temporary folder to hold the files for binary processing like so:

    <add key="CuteWebUI.AjaxUploader.TempDirectory" value="~/UploaderTemp"/>
    Add the above to your web.config file under <appSettings> section.

     
    NOTE: when deployed to the server, this folder (UploaderTemp) needs proper permissions to allow the process to delete the files. They'll be deleted once the file has been converted to binary and already in the database.  During testing on live server if you get permissons error or get prompted to "login" to this folder, you know the permissions are not set correctly.
     
     

    On your .aspx page you'll have your uploader object:


     <cc1:Uploader ID="Uploader1" runat="server" MultipleFilesUpload="true" InsertText="Select Multiple Files" ManualStartUpload="true" OnFileUploaded="FileUploaded" OnUploadCompleted="Uploader1_UploadCompleted">
                 <InsertButtonStyle CssClass="UploadButton"  />
                <CancelButtonStyle CssClass="CancelButton" />
     </cc1:Uploader>
     
    Which has two main events:  OnFileUploaded and OnUploadCompleted:
    OnFileUploade will loop through each of the files, convert to stream and write to database:
    protected void FileUploaded(object sender, CuteWebUI.UploaderEventArgs args)
        {
           byte[] docBinary = new byte[args.FileSize];
            using (Stream stream = args.OpenStream())
            {
                stream.Read(docBinary, 0, docBinary.Length);
                //also grab other upload form data to write to database as well here (Name, email etc...)
                //sql objects and instert statement here
            
            }
         

    OnUploadComplete is where we deleted the copies of the files used for the Stream process:

    protected void Uploader1_UploadCompleted(object sender, UploaderEventArgs[] args)
        {
            for(int i = args.Length - 1; i>=0; i--)
            { args[i].Delete();
            }
        }

    Downloading Files:
    On a different .aspx you have a Grid / Repeater or similar that has a hyperlink field that's converted to a template field:
      <asp:TemplateField HeaderText="File Name / Download" SortExpression="File_Name">
                                <ItemTemplate>
                                    <asp:Hyperlink ID="hlink1" runat="server" Text='<%# Eval("File_Name") %>' NavigateUrl='<%# Eval("File_ID","DownloadHandler.ashx?File_ID={0}") %>' Target="_blank" />
                                </ItemTemplate>
       </asp:TemplateField>

    The link points to a generic file handler: .ashx file callded DownloadHandler.ashx and has query string parameters tacked on to the end: File_ID={0}

    The code for DownloadHandler.ashx looks something like this:
    public class DownloadHandler : IHttpHandler
    {
       
        public void ProcessRequest (HttpContext context)
        {

               
            SqlConnection sqlConn;
            SqlCommand sqlComm;
            string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
            conn = new SqlConnection(connString);
            comm = new SqlCommand("SELECT File_ID, File_Name, File_ContentType, File_Binary FROM DocumentFiles WHERE File_ID=@File_ID", conn);
            comm.CommandType = CommandType.Text;
            SqlParameter documentID = new SqlParameter("@File_ID", SqlDbType.Int);
            documentID.Value = context.Request.QueryString["File_ID"];
            comm.Parameters.Add(documentID);
           
            sqlConn.Open();
            SqlDataReader dataReader = comm.ExecuteReader();
            dataReader.Read();
           
            try
            {
                string fileName = (string) dataReader["File_Name"];
                context.Response.ContentType = (string) dataReader["File_ContentType"];
                context.Response.BinaryWrite((byte[])dataReader["File_Binary"]);
                context.Response.AddHeader("Content-Disposition","attachment;fileName=" + fileName + ""); // this line will force the document to be downloaded instead of opened inside the browser...
           }
            catch (System.Exception)
            {throw;
            }
           
            dataReader.Close();
            sqlConn.Close();

        }   
     
     
    UPDATED: for your temp directory permissions: II6 add IIS_WPG user/full control.  In IIS7 add IIS_IUSERS with full control
     
  •  08-09-2012, 10:07 AM 74391 in reply to 74380

    Re: How To: Setup Direct to Database Upload/Download

    Hi dougm,
     
    Thanks for share it.
     
    Regards,
     
    Ken 
View as RSS news feed in XML