天天看點

檔案下載下傳的多種方法

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();

            }

            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 (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));

            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();

        catch (Exception e)

            Console.Write(e.Message);