How to download file with asp.net on buttton's onClick event?

前端 未结 5 1939
时光取名叫无心
时光取名叫无心 2021-02-06 15:37

I have a String variable (in C#) that contain the full path of PDF file on my server (like that \"~/doc/help.pdf\").

I want that in click on button, this file will down

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 16:03

    I would suggest the following to be placed into your button click event code.

    This will provide the user with a popup to download the file. I've tested it thoroughly and use it in production code.

    void btnDownloadFile_Click(object sender, EventArgs e)
    {    
        string strLocalFilePath = "~/doc/help.pdf";
        string fileName = "help.pdf";
    
        Response.Clear();
    
        Stream iStream = null;
    
        const int bufferSize = 64 * 1024;
    
        byte[] buffer = new Byte[bufferSize];
    
        int length;
    
        long dataToRead;
    
        try
        {
            iStream = new FileStream(strLocalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            dataToRead = iStream.Length;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    
            while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, bufferSize);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    buffer = new byte[bufferSize];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    //prevent infinate loop on disconnect
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            //Your exception handling here
        }
        finally
        {
            if (iStream != null)
            {
                iStream.Close();
            }
            Response.Close();
        }
    }
    

提交回复
热议问题