文件下载的多种方法

if (Request["name"] != null)
        {
            try
            {
                string FileName = MyCrypt.Decrypt(Request["name"]);
                //string FilePath = Server.MapPath(string.Format("UploadFile/{0}", FileName));

                string strPhyPath = Server.MapPath(string.Format("UploadFile/{0}", FileName));//fileurl是文件的相对地址
                if (File.Exists(strPhyPath))
                {
                    //取文件大小
                    FileStream MyFileStream;
                    uint FileSize1;
                    MyFileStream = new FileStream(strPhyPath, FileMode.Open, FileAccess.Read, FileShare.None);
                    int iConverTemp = Convert.ToInt32(MyFileStream.Length);
                    FileSize1 = (uint)(iConverTemp);
                    MyFileStream.Close();

                    //存在,下载
                    Page.Response.ContentType = "APPLICATION/OCTET-STREAM";
                    Page.Response.AddHeader("Content-length", FileSize1.ToString());//下载文件长度
                    Page.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                    Page.Response.WriteFile(strPhyPath);
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    //MessageBox.Show("该附件不存在或者已被删除,请联系管理员处理!", this);
                    Response.Write("<script>alert('该附件不存在或者已被删除,请联系管理员处理!');if(window.parent!=window) window.parent.close(); else {window.opener=null;window.open(',','_self');window.close();}</script>");
                    return;
                }

                //第二种下载方法
                ////Response.ContentType = "application/x-zip-compressed"; itjeff modified.
                //Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)));
                //Response.TransmitFile(FilePath);


                //第三种下载方法
                //Response.ContentType = "application/ms-winword";
                //Response.ContentEncoding = System.Text.Encoding.Default;
                //Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                //Response.WriteFile(FilePath);
                //Response.End();


                //第四种下载方法
                ////以字符流的形式下载文件
                //FileStream fs = new FileStream(FilePath, FileMode.Open);
                //byte[] bytes = new byte[(int)fs.Length];
                //fs.Read(bytes, 0, bytes.Length);
                //fs.Close();
                //Response.ContentType = "application/octet-stream";
                ////通知浏览器下载文件而不是打开
                //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                //Response.BinaryWrite(bytes);
                //Response.Flush();
                //Response.End();

            }
            catch (Exception er)
            {
                Response.Write(string.Format("<script>alert('下载附件时发生异常,异常信息为:{0}');</script>", er.Message));
            }
        }

//文件下载方法

DownLoadFile(ps_dl.FilePath, ps_dl.ViewName,ref err);

private bool DownLoadFile(string filePath,string fileName,ref string err)
    {
        if (File.Exists(Server.MapPath(filePath)))
        {
            string fileExtent = Path.GetExtension(filePath);
            string fileAllName = fileName + fileExtent;
            FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(fileAllName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('aaa');window.close();", true);
            Response.Flush();
            Response.Write(" <script> window.openner=null;window.close(); </script> ");
            Response.End();

            return true;
        }
        else
        {
            err = "文件不存在!";
            return false;
        }
    }

//文件下载封装方法

public void DownLoadFile(string path)
    {
        if (path != "")
        {
            string serverpath = Server.MapPath(path);
            if (File.Exists(serverpath))
            {
                string filename = path.Split('/').Last().Split('.').First();
                PageTools.DownloadFile(Response, filename, Server.MapPath(path), false);
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('该路径无效,文件已删除或不存在!');</script>");
            }

        }
    }

    public void DeleteFile(string path)
    {
        path = Server.MapPath(path);
        if (path != "")
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
    }

/// <summary>
    /// 以流方式下载文件,并删除文件
    /// </summary>
    /// <param name="response">页面HttpResponse</param>
    /// <param name="fileName">下载的时候显示的文件名</param>
    /// <param name="filePath">原始文件的物理路径</param>
    /// <param name="isDel">下载后是否删除文件,true表示删除,false表示不删除</param>
    public static bool DownloadFile(HttpResponse response, string fileName, string filePath, bool isDel)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bs = new byte[fs.Length];
            fs.Read(bs, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            response.ContentType = "application/octet-stream";
            response.AppendHeader("Content-Disposition", "attachment;filename="
                + HttpUtility.UrlEncode(fileName + Path.GetExtension(filePath), System.Text.Encoding.UTF8));

            response.BinaryWrite(bs);
            if (isDel)
            {
                File.Delete(filePath);
            }

            //HttpContext.Current.ApplicationInstance.CompleteRequest();
            response.Flush();
            response.End();
            return true;
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
            return false;
        }
    }

原文地址:https://www.cnblogs.com/itjeff/p/3786160.html