Get path, filename and extension
16th March, 2011
It is often interesting when you have to download an image to put into cache to get the name and the extension of the file in the URL.
For this tutorial, you need to declare a table in your AIModel variables, I named it tTable.
create a function named getFile and add the variable sFileURL as parameter.
Get the path
Start the script by clearing the table data:
table.empty ( this.tTable ( ) )
Use now the string.explode. The delimiter will be the “/” character. Use the sFileURL variable plus “/” as first parameter, the table as second parameter, and “/” as delimiter (third parameter).
string.explode ( sFileURL..”/”, this.tTable ( ), “/” )
The last item of the table is the filename with its extension:
Get the filename and the extension
local sFilenameAndExtension = table.getLast ( this.tTable ( ) )
Logically, the path of the file is the URL without the file and the extension:
local sPath = string.getSubString ( sFileURL, 0, string.getLength ( sFileURL ) – string.getLength ( sFilenameAndExtension ) )
Now you have to separe the filename to its extension, you must find the “.” symbol:
local nDotIndex = string.findFirst ( sFilenameAndExtension, “.”, 0 )
The extension is the part at the right of the string:
local sExtension = string.getSubString ( sFilenameAndExtension, nDotIndex, string.getLength ( sFilenameAndExtension ) – nDotIndex )
And the filename is the other part:
local sFilename = string.getSubString ( sFilenameAndExtension, 0, string.getLength ( sFilenameAndExtension ) – string.getLength ( sExtension ) )
It is finished, you can return the results:
return sPath, sFilename, sExtension