Question

I wrote a Ihttphandler in order to download files :

public class DescargaFichero : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Okiservice usuariosbd = new Okiservice();

        usuariosbd.CommandTimeout = 9000;



        byte[] datos;
        //var lista = usuariosbd.ficheros
        //    .Where (p=> p.iddoc==iddoc)
        //    .Select(p => new { IdDoc = p.iddoc, Area = p.area, Nombre = p.nombreweb, Descripcion = p.descripcion, FicheroReal = p.SystemFile, Tamano = p.Size,Extension=p.Extension,MIME=p.Content_Type }).FirstOrDefault();

        int id= Convert.ToInt32(context.Request["Id"]);

        var lista = (from binario in usuariosbd.Documentos_Binario
                     join docs in usuariosbd.Documentos on binario.FK_Adjunto equals docs.FK_Adjunto
                     join tipo in usuariosbd.Content_Type on binario.FileType equals tipo.id_content
                     where docs.iddoc == id
                     select new { binario.SystemFile, tipo.Content_Type1, docs.nombreweb }).First();

        datos = lista.SystemFile;

        //System.Web.HttpContext.Current.Response.ContentType =
        //    "application/vnd.ms-excel";


       string tipocontenido= lista.Content_Type1;

       string nombrefichero = lista.nombreweb;


        System.IO.Stream iStream = null;

        // Buffer to read 10K bytes in chunk:
        byte[] buffer = new Byte[10000];

        // Length of the file:
        int length;

        // Total bytes to read:
        long dataToRead;

        // Identify the file to download including its path.
        string filepath = "DownloadFileName";

        // Identify the file name.
        //string filename = System.IO.Path.GetFileName(filepath);

        try
        {
            // Open the file.
            //iStream = new System.IO.FileStream(sfichero, System.IO.FileMode.Open,
            //            System.IO.FileAccess.Read, System.IO.FileShare.Read);

            MemoryStream input = new MemoryStream(datos);
            iStream = input;


            // Total bytes to read:
            dataToRead = iStream.Length;

            System.Web.HttpContext.Current.Response.ContentType = tipocontenido;
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + nombrefichero);

            // Read the bytes.
            while (dataToRead > 0)
            {
                // Verify that the client is connected.
                if (System.Web.HttpContext.Current.Response.IsClientConnected)
                {
                    // Read the data in buffer.
                    length = iStream.Read(buffer, 0, 10000);

                    // Write the data to the current output stream.
                    System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);

                    // Flush the data to the HTML output.
                    System.Web.HttpContext.Current.Response.Flush();

                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            // Trap the error, if any.
            System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                //Close the file.
                iStream.Close();
            }
            System.Web.HttpContext.Current.Response.Close();
        }



    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

and It is called by a JQuery AJAX function where I pass the Id Argument, which is the id of the file that has to be downloaded:

function obtenerFichero(id) {
                $(document).ready(function () {

                    $.ajax({
                        type: "POST",
                        url: "../HELPDESK/DescargaFichero.ashx",

                        data:"Id="+id,

                        success: function (msg) {

                        }

                    });
                });
            }

When I run the debug I can see that I´m getting the correct data in the IHttpHandler at response time: => System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); but nothing happens in the webpage , nothing at all.

Thank you!

Was it helpful?

Solution

I believe the issue lies in that your code attempts to download a file from an AJAX call, which is not possible.

To trigger a file to be downloaded, change the window.location to the URL of your handler. Since you use Content-Disposition, it should prompt to download.

function obtenerFichero(id) {
   window.location.href = '../HELPDESK/DescargaFichero.ashx?ID=' + id;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top