开发者

ASP.NET MVC File method

开发者 https://www.devze.com 2023-04-09 12:15 出处:网络
Hi I would like to send user a file but without showing the url. Using File method the problem is that I have my file in another server and so I have only url not a virtual path, I tried to use WebCl

Hi I would like to send user a file but without showing the url.

Using File method the problem is that I have my file in another server and so I have only url not a virtual path, I tried to use WebClient to get file bytes to use in File method but 开发者_如何转开发it's quite slow, my files are greater than 20 Mb!

Any idea on how can I do this without get all file bytes before sending them to my user?

This is my code inside my Controller:

            using (WebClient Client = new WebClient())
            {
                byte[] fileContent = Client.DownloadData(fileUrl);

                return File(fileContent, "application/octet-stream", fileName);
            }

Thanks


You can read from your server in blocks and write them directly to your output stream. Play with the block size to tweak performance.

using (var client = new WebClient()) {
    using (Stream data = client.OpenRead(fileUrl)) {
        using (var reader = new BinaryReader(data)) {
            var buffer = new byte[8192];
            int nread;
            while ((nread = reader.Read(buffer, 0, buffer.Length)) > 0)
                Response.OutputStream.Write(buffer, 0, nread);
        }
    }
}
return null;


You can use Response.BinaryWrite to write binary data to the output stream.

You can do this in multiple chunks if you need to, then flush and end the response when it's finished.

0

精彩评论

暂无评论...
验证码 换一张
取 消