[Tip] Opening a file stored in a blob
by Bob Cusick
Servoy USA
You can store any information in BLOB fields in Servoy ("media" fields). This can be QuickTime movies, Word files, etc. then you can extract that data and open it with the native application on whatever platform the client is using. One of the caveats is that you need to STORE at least the 3 letter EXTENSION of the file when they load it into the database. This means that you have to have your own button to load the binary data - and NOT just have the user right click on media field. Here's the code you'll need to load the data into the database and store the 3 letter extension:
//I have a global for the last path opened - this is OPTIONAL
//The parameter "1" means show both files and folders
if(globals.gLastPath)
{
var fileName = plugins.file.showFileOpenDialog(1, globals.gLastPath)
}
else
{
var fileName = plugins.file.showFileOpenDialog(1)
}
//the global "gUserFileSeparator" holds either "\" for PC or "/" for Mac OS X
var x = application.getOSName()
globals.gUserFileSeparator = '\\'
if(x.indexOf('Mac',1) != -1)
{
globals.gUserFileSeparator = '/'
}
if(fileName != null)
{
//reads the file into a variable
var data = application.readFile(fileName)
//set the variable "fName" to the entire path of the document
var fName = fileName.getPath()
//get the file name
//the global "gUserFileSeparator" holds either "\" for PC or "/" for Mac OS X
var x = fName.lastIndexOf(globals.gUserFileSeparator)
//sets variable "name" to the name of the file
var name = fName.substring(x+1)
//set up the directory to open with next time
globals.gLastPath = fName.substr(1, fName.lastIndexOf(globals.gUserFileSeparator))
//get the file extension
x = name.lastIndexOf('.')
var ext = name.substring(x)
//add the new image record
forms.images.controller.newRecord()
forms.images.image = data
forms.images.name_ext = ext
forms.images.name_orig = name
application.updateUI()
}
I stored the data, extension and name of the file in the database record. Now, to open the image - here's the code:
//Creates a temporary file (will be deleted after application shutdown)
//get the position of the last "." in the file name
var a = forms.dialog_images.name_orig.lastIndexOf(".")
var b = "temp"
//get the 3 letter extension - INCLUDING the "."
var c = forms.dialog_images.name_orig.substring(a)
//create a temporary file that will be auto-deleted by Servoy when client is exited
var filename = application.createTempFile(b,c)
//write the binary data out to disk at the temporary file location
application.writeFile(filename,forms.dialog_images.image);
//launch the document with external application
if(utils.stringMiddle(application.getOSName(),1,7) == "Windows")
{
application.executeProgramInBackground('rundll32', 'url.dll,FileProtocolHandler',filename)
}
else
{
application.executeProgram('open', filename);
}