Attachments

Upload an Attachment to a New Record

Description
This customization shows how to upload an attachment such as an image or word document to a record.
Variables
Upload Button Control
Select the upload button
Table Name
Select the table having image type column(s)
Attachment filename
Select the field containing name of the attachment
Attachment Field
Select the field containing the attachment
Applies to
P_Upload Button Control class
Code
 
/// 
/// Click handler for Button uploads an attachment to a 
/// new record in database.
///    
public override void ${Upload Button Control}_Click(Object sender , EventArgs args)
{
    System.Web.UI.HtmlControls.HtmlInputFile inputFile;   
    inputFile = (System.Web.UI.HtmlControls.HtmlInputFile)((BaseApplicationPage)this.Page).FindControlRecursively("inputFile");
    if ((!(inputFile.PostedFile == null) && (inputFile.PostedFile.ContentLength > 0)))
    {
        // Get the name of the file to be uploaded        
        string path = inputFile.PostedFile.FileName;
        int LastIndex = path.LastIndexOf("\\");
        string fileName = path.Substring((LastIndex + 1));
        int intDocLen = inputFile.PostedFile.ContentLength;
        System.IO.Stream docStream = inputFile.PostedFile.InputStream;
        
        // If you are using Access DB, then contents have to be of OLE type
        // If SQL server then contents have to be of image type
        byte[] contents =  new byte[intDocLen];
        docStream.Read(contents, 0, intDocLen);
        try 
        {
            DbUtils.StartTransaction();
            
            // Create a new record.
            ${${Table Name}RecordClassName} rec = new ${${Table Name}RecordClassName}();

            // Populate the new record with attachment and other information.
            // Where ID is the primary key
            // rec.ID = "5"
            rec.${Attachment Field} = contents;
            rec.${Attachment filename} = fileName;

            // Save the new record.
            rec.Save();
            DbUtils.CommitTransaction();
            this.Page.Response.Write("The file has been uploaded to DB.");
        }
        catch (Exception exc)
        {
            this.Page.Response.Write(("Error: " + exc.Message));
            DbUtils.RollBackTransaction();
        }
        finally 
        {
            DbUtils.EndTransaction();
        }
    }
    else 
    {
        this.Page.Response.Write("Please select a file to upload.");
    }
}
     

Terms of Service Privacy Statement