Marco Dinatsoli
Marco Dinatsoli

Reputation: 10590

TransmitFile is not working

I have a file, and it is full path (plus the file name) is in this variable:

fileTemporary

i want to download that file to the client.

i do this:

 HttpContext.Current.Response.TransmitFile(fileTemporary);

but nothing happen, i mean when i click the button, this file executes, but nothing is being downloaded to the client. i don't see any file on the browser of the client.

what mistake did i do please?

Upvotes: 0

Views: 3727

Answers (1)

Anton Norka
Anton Norka

Reputation: 2322

If you use MVC you can:

[HttpGet]
        public virtual ActionResult GetFile(string fileTemporary)
        {
            // ...preparing file path... init fileTemporary.

            var bytes = System.IO.File.ReadAllBytes(fileTemporary);
            var fileContent = new FileContentResult(bytes, "binary/octet-stream");
            Response.AddHeader("Content-Disposition", "attachment; filename=\"YourFileName.txt\"");

            return fileContent;
        }

If you use ASP.NET or whatever you can use following (sorry, my old code, but you can understand approach):

var bytes = System.IO.File.ReadAllBytes(fileTemporary);
SendFileBytesToResponse(bytes, fileName);

public static bool SendFileBytesToResponse(byte[] bytes, string sFileName)
        {
            if (bytes!= null)
            {
                string downloadName = sFileName;
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition",
                                   "attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
                response.Flush();
                response.BinaryWrite(bytes);
                response.Flush();
                response.End();
            }

            return true;
        }

Without reingeneering your solution:

System.Web.HttpContext.Current.Response.Clear();

System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
                "attachment; filename=" + fileName);  

System.Web.HttpContext.Current.Response.TransmitFile(fileName);

If you would like browser to interpret you file right, you will need to specify header "Content-Type" more precise. Please see list of content types

Upvotes: 1

Related Questions