Upload to FTP from Stata

You can easily use Stata's copy command to download files from the web, but it does not allow you to send your files in the other direction. To do that you better use an FTP client on your computer. Luckily, this is something you can do from the command prompt in Stata. Here I show you how it can be done with the Windows utility ftp.exe, but the same logic applies to many other scriptable FTP clients.

You can think of this as a two-step procedure. First we need to create a text file which includes all the commands we want the FTP client to execute. We can do that in a text editor or through Stata's file functions. If using ftp.exe, the final script should look something like this:

open [url]
[username]
[password]
lcd [local folder]
cd [remote folder]
send [filenames]
disconnect
quit

When the script is done, we can run the FTP program by issuing a shell command in Stata. To run ftp.exe, turn off interactive prompting and run the script file, just type the following:

!ftp -i -s:[filename]

However, for many applications, it may be more convenient to write a program which does it all at once. The code below creates a program which requires a filelist, url, username and password. It also allows you to specify a different local folder (default is the working directory) and a different remote folder (default is the root folder of your FTP user). What you want as arguments and what you want in the program code will differ from case to case, so adjust the code to your liking.

capture program drop upload
program define upload
syntax anything, url(string) user(string) password(string) [lcd(string) rcd(string)]
if "`lcd'" == "" local lcd = "`c(pwd)'"
file open temp using temp.txt, write replace
local fwt file write temp
`fwt' "open `url'" _n
`fwt' "`user'" _n
`fwt' "`password'" _n
`fwt' "lcd `lcd'" _n
if "`rcd'" != "" `fwt' "cd `rcd'" _n
foreach var in `anything' {
   `fwt' "send `var'" _n
}
`fwt' "disconnect" _n
`fwt' "quit" _n
file close temp
!ftp -i -s:temp.txt
erase temp.txt
end

For more FTP commands, see for example this site.