0

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

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

I want to send file to the user not save the file locally. My file web server has all the files and my application must send to users those file without showing their urls.
@JasonMenny sorry for the misunderstanding. Have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.