Download SFTP Files Indirectly through a Web Site

Question:

I am doing a project that requires a web site to list files from an SFTP server and allow the visitor to download them.  Following the examples on your site, it was very easy to list the files.  However, you have no example of downloading a file to the user, only to the local filesystem.  Do you have any code that could help me with this?

Answer:

This is a common question.  To restate the situation:

  1. There  is an SSH/SFTP server on your private network accessible from the server-side code running on your web server, but not accessible to the outside world.
  2. The need is to deliver files from this server to an end-user located anywhere on the Internet using only a browser.

The solution:

  1. The end-user clicks on a link or form “submit” button that sends an HTTP request (GET or POST) to your web server.
  2. The page handling this request includes server-side code, which (of course) runs on the web server.  It needs to download the file from the SSH/SFTP server to either a temporary file (on the web server) or perhaps directly into an in-memory byte array.
  3. The file data is then sent in an appropriate HTTP response, with correct Content-Type header indicating the type of data.  If using ASP/ASP.NET, it will probably involve calling Response.BinaryWrite.