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 Overrides Sub ${Upload Button Control}_Click(ByVal sender As Object, ByVal args As EventArgs)
    Dim inputFile As System.Web.UI.HtmlControls.HtmlInputFile
    inputFile = CType(CType(Me.Page, BaseApplicationPage).FindControlRecursively("inputFile"), System.Web.UI.HtmlControls.HtmlInputFile)
    If (Not inputFile.PostedFile Is Nothing) And _
       (inputFile.PostedFile.ContentLength > 0) Then

        ' Get the name of the file to be uploaded        
        Dim path As String = inputFile.PostedFile.FileName
        Dim LastIndex As Integer = path.LastIndexOf("\")
        Dim fileName As String = path.Substring(LastIndex + 1)
        Dim intDocLen as Integer = inputFile.PostedFile.ContentLength
        Dim docStream As System.IO.Stream = 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
        Dim contents(intDocLen) As Byte
        docStream.Read(contents, 0, intDocLen)
        Try
            DbUtils.StartTransaction()

            'Create a new record.
            Dim rec As ${${Table Name}RecordClassName} = 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()
            Me.Page.Response.Write("The file has been uploaded to DB.")
        Catch exc As Exception
            Me.Page.Response.Write("Error: " & exc.Message)
            DbUtils.RollBackTransaction()
        Finally
            DbUtils.EndTransaction()
        End Try
    Else
        Me.Page.Response.Write("Please select a file to upload.")
    End If

End Sub

     

Terms of Service Privacy Statement