Friday, May 19, 2006

Using LotusScript to import an image resource

A few years back I wrote some code and co-authored an article on using the Java and DXL Toolkit to import image resources into the domino design. I figured as my first blog entry I'd write about the same subject utilizing the latest LotusScript APIs in release 6x to import an image resource into a Lotus Domino design...

We start with a simple notes form with a single file upload control and a submit button that invokes an agent on submit.

The agent code below handles importing the imageSub Initialize
On Error Goto MyErr

Dim s As New NotesSession
Dim db As NotesDatabase
Dim col As NotesDocumentCollection
Dim doc As NotesDocument
Dim fileNames As Variant Dim item As NotesRichTextItem
Dim bean As FileBean
Dim factory As New FileBeanFactory()
Dim resource As ImageResource

Set db = s.CurrentDatabase
Set doc = s.DocumentContext

'creates the object collection of FileBeans.
Call factory.createFileBeans(doc)
'now get the bean based on one of the file names in the doc
fileNames = Evaluate("@AttachmentNames",doc)
'get the FileBean object from the factory using a file name as the key
Set bean = factory.getFileBean(fileNames(0))
'set the resource to a new image resource based on FileBean
Set resource = New ImageResource(bean)
'save the image resource to database (note can be any database)
Call resource.saveToDatabase(db)

Exit Sub

Dim errBody As String
errBody =Lsi_info(2) & " " & Str(Err) & ": " & Error$ & " on line: " & Erl()
Print errBody

Exit Sub

End Sub

In the above agent you will notice that I've created three custom classes to facilitate the importation of the image resource:

  • FileBean (temporary data store for a single attachment containing the base64 encoded file data)
  • FileBeanFactory (factory class that creates a FileBean per attached file in the document using DXLExporter and SAX parser to create a collection of FileBean(s))
  • ImageResource (class that takes the bean and does the import using the DXLImporter to passed in database)

In a nutshell this is pretty much it. There is a BeanFactoryHelper class that is wrapped by FileBeanFactory. If you are interested in seeing how the FileBean is built using the SAX parser look there. There is also a handy collections object I've built and use in most of my apps. It is sort of a hybrid between a HashMap and an ArrayList.... containing methods to get object handles via index, and string keys along with some enumeration helpers like getFirst, getNext, getNth(i) etc... To try out the app download .zip and extract the .nsf to you domino server. Once setup on domino launch the Upload_Image?OpenForm url command on your development domino server using http://yourhost/ImageResourceImport.nsf/Upload_Image?OpenForm