Friday, November 7, 2014

Copy to FTP in Classic ASP (JScript)

Recently I had the need to FTP some files in the old Classic ASP platform. The catch is that I need it to be in JScript (Javascript for IIS). In my experience most people use VB script in their ASP environment,. the past few years I have grown to prefer using JScript. If you'd like to use VBScript to FTP then might I suggest this great source. It is from this that I have adapted my JS version.

FTP in ASP (JScript)

In my current environment I never use serverside JScript to render HTML, rather only to serve in a JSON based API format. For the purposes of sharing, I trimmed down the scaffolding into the bare necessities and was left only needing a JSON polyfill: JSON polyfill that works in ASP JScript.

var ftp = (function() { /* * Copy a file(s) to a directory on a remote FTP server. * * Adapted from the very usefull post @ http://benmeg.com/code/asp/ftp.asp.html */ function copyTo(address, username, password, remote_directory, files_to_put, isBinary) { var objFSO = Server.CreateObject("Scripting.FileSystemObject"), oScript = Server.CreateObject("WSCRIPT.SHELL"), oFileSys = Server.CreateObject("Scripting.FileSystemObject"), objTextFile, oScriptNet, oFile, strCMD, strTempFile, strCommandResult = '', uniqueNumber = '__'; // This is for you to implement a random key on your system (if required). // Build our ftp-commands file objTextFile = objFSO.CreateTextFile(Server.MapPath('ftpCommand' + uniqueNumber + '.ftp')); objTextFile.WriteLine('lcd ' + Server.MapPath('.')); objTextFile.WriteLine('open ' + address); objTextFile.WriteLine(username); objTextFile.WriteLine(password); // Check to see if we need to issue a 'cd' command if (remote_directory != '') objTextFile.WriteLine('cd ' + remote_directory); objTextFile.WriteLine('prompt'); // If the file(s) is/are binary (i.e. .jpg, .mdb, etc..) if (isBinary) objTextFile.WriteLine('binary'); // If there are multiple files to put, we need to use the command 'mput', instead of 'put' if (files_to_put.indexOf('*') > -1) objTextFile.WriteLine('mput ' + files_to_put); else objTextFile.WriteLine('put ' + files_to_put); objTextFile.WriteLine('bye'); objTextFile.Close(); delete objTextFile; // Pipe output from cmd.exe to a temporary file strTempFile = Server.MapPath('ftpOutput-' + uniqueNumber + '.ftp'); // Use cmd.exe to run ftp.exe, parsing our newly created command file oScript.Run('cmd.exe /c ' + 'ftp.exe -s:' + Server.MapPath('ftpCommand' + uniqueNumber + '.ftp') + ' > ' + strTempFile, 0, true); oFile = oFileSys.OpenTextFile(strTempFile, 1, false, 0); // Grab output from temporary file strCommandResult = oFile.ReadAll(); oFile.Close(); // Delete the temporary & ftp-command files oFileSys.DeleteFile(strTempFile, true); objFSO.DeleteFile(Server.MapPath('ftpCommand' + uniqueNumber + '.ftp'), true); delete oFileSys; delete objFSO; return { result: strCommandResult.split('\r\n') }; } return { copyTo: copyTo }; })();

Which results in: