Response.OutputStream.Write()向浏览器显示数据而不是下载

时间:2018-01-03 16:31:08

标签: c# asp.net filestream httphandler

我使用IHttpHandler从Server下载文件。一切正常。 但它在浏览器上显示数据而不是下载它。我需要从服务器下载文件,就像我们从其他服务器下载一样。

有人可以建议我,我该怎么做才能下载文件, 或者下载文件的便捷方式是什么(pdf,mp4等)。

public void ProcessRequest(HttpContext context)
    {

        string strPathName = "";
        if (context.Request.QueryString["fileName"] != null)
        {
            strPathName = context.Request.QueryString["fileName"].ToString();
        }
        string filename = context.Server.MapPath("~/MyPath/" + strPathName);

        System.IO.Stream oStream = null;

        oStream =
            new System.IO.FileStream
                (path: filename,
                mode: System.IO.FileMode.Open,
                share: System.IO.FileShare.Read,
                access: System.IO.FileAccess.Read);
        try
        {
            context.Response.ClearHeaders();

            context.Response.Buffer = false;

            context.Response.ContentType = "application/octet-stream";


            context.Response.AddHeader("Content-Disposition", "attachment");

            long lngFileLength = oStream.Length;

            context.Response.AddHeader("Content-Length", lngFileLength.ToString());

            long lngDataToRead = lngFileLength;

            while (lngDataToRead > 0)
            {

                if (context.Response.IsClientConnected)
                {

                    int intBufferSize = 8 * 1024;

                    byte[] bytBuffers =
                        new System.Byte[intBufferSize];

                    int intTheBytesThatReallyHasBeenReadFromTheStream =
                        oStream.Read(buffer: bytBuffers, offset: 0, count: intBufferSize);

                    context.Response.OutputStream.Write
                        (buffer: bytBuffers, offset: 0,
                        count: intTheBytesThatReallyHasBeenReadFromTheStream);

                    context.Response.Flush();

                    lngDataToRead =
                        lngDataToRead - intTheBytesThatReallyHasBeenReadFromTheStream;
                }
                else
                {
                    lngDataToRead = -1;
                }
            }
        }
        catch { }
        finally
        {
            if (oStream != null)
            {
                oStream.Close();
                oStream.Dispose();
                oStream = null;
            }
           context.Response.Close();
        }
    }

1 个答案:

答案 0 :(得分:1)

您不能通过ajax直接下载文件,它只会将数据返回到页面代码中的JS变量,而不是触发传统的请求和下载。

您的按钮需要发出标准HTTP请求,而不是ajax调用。