IHTTPHANDLER /下载文件。网页上没有任何内容

时间:2012-06-20 10:22:10

标签: jquery asp.net ihttphandler

我写了一个Ihttphandler来下载文件:

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;
        }
    }
}

并且它由JQuery AJAX函数调用,我传递了Id Argument,它是必须下载的文件的id:

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

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

                        data:"Id="+id,

                        success: function (msg) {

                        }

                    });
                });
            }

当我运行调试时,我可以看到我在IHttpHandler中获取了正确的数据 在响应时间: => System.Web.HttpContext.Current.Response.OutputStream.Write(buffer,0,length); 但网页上什么也没发生,什么也没发生。

谢谢!

1 个答案:

答案 0 :(得分:2)

我认为问题在于您的代码尝试从AJAX调用下载文件,这是不可能的。

要触发要下载的文件,请将window.location更改为处理程序的URL。由于您使用Content-Disposition,因此应提示下载。

function obtenerFichero(id) {
   window.location.href = '../HELPDESK/DescargaFichero.ashx?ID=' + id;
}