Warm tip: This article is reproduced from serverfault.com, please click

Download from FTP and serve result using streams

发布于 2021-10-20 16:20:34

In my Asp.Net MVC application I want to implement a method that allows me to download files stored on an FTP. I'd like to compete the following code to use streams and avoid downloading the entire file first and then serving them as FileResult

   public FileResult getBigFileFromFTP()
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp-location.com/test/bigfile.zip");

        request.Method = WebRequestMethods.Ftp.DownloadFile;
         
        request.Credentials = new NetworkCredential("ftpuser", "ftppwd");

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        
        //Missing code... I would like to serve the file during FTP download


           

    }
Questioner
treep
Viewed
0
Panagiotis Kanavos 2021-10-21 16:09:29

You can create a FileResult from a stream. By default ASP.NET Core buffers a response before sending it to the browser. This can be a problem with big files. To avoid this you need to disable buffering.

Try using :

Response.BufferOutput = false;
return File(responseStream);