简体   繁体   中英

C# WebClient - downloading a file from an ftp to client

I'm looking to pass in an authorization code from a form to a controller, evaluate the code and if it matches, call an ftp site to trigger a download event where the user receives a file.

I have two constraints, 1. I need to pass the ftp site credentials, 2. I need to hide the url from the user. Once logged in, 'as a user' on the ftp site, I can paste the url into the browser and it triggers an auto download event of the zip file. I think I have to use the below approach to pass off the credentials, however, I want to avoid having to first download the file onto my server to then turn around and pass it to the user. (double the processing time right?) I need a way to hand off the credentials to the ftp site and trigger the download event to go straight to the users machine to the usual 'download' folder...

I have no clue on how to do this and cant find any solid references. Most are showing how to process it to the user from the server because the file is stored where the application lives. Any references or samples is appreciated!

Thanks in advance!

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AuthCode(string code)
    {
        var username = "someuser";
        var password = "somepass";

        if(code.Equals("$%^123XYZ"))
        {
            var url = "ftp://url.zip";
            var fileName = "Some Name";

            var client = new WebClient();
            client.Credentials = new NetworkCredential(username, password);
            client.DownloadFile(url, fileName);

            return View("GoodCode");
        }
        else
        {
         return View("BadCode");
        }
    }

FtpWebRequest class supports stream in response. Here is an example of file download from FTP using stream.

To return a stream in the action FileStreamResult can be used pass the stream into the response

return new FileStreamResult(stream, "application/pdf")
 {
     result.FileDownloadName = "somefile.pdf";
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM