天天看點

.net 代碼實作檔案下載下傳

如果下載下傳時直接通過通路檔案的路徑的方法,在下載下傳.txt等檔案時,浏覽器會預設打開檔案, 通過下面的方法,就可以避免浏覽器打開檔案,直接提示儲存檔案:

    /// <summary>

    /// 檔案下載下傳

    /// </summary>

    /// <param name="savename">儲存時的檔案名</param>

    /// <param name="FullFileName">下載下傳檔案路徑   Server.Mappath(filepath)</param>

    /// <param name="Response">Response</param>

    public static void savefile(string savename, string FullFileName, System.Web.HttpResponse Response)

    {

        try

        {

            FileInfo DownloadFile = new FileInfo(FullFileName);

            if (DownloadFile.Exists)

            {

                Response.Clear();

                Response.ClearHeaders();

                Response.Buffer = false;

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

                Response.AppendHeader("Content-Disposition", "p_w_upload;filename=" + System.Web.HttpUtility.UrlEncode(savename, System.Text.Encoding.UTF8));

                Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

                Response.TransmitFile(DownloadFile.FullName);

                Response.Flush();

                Response.End();

            }

            else

                //檔案不存在

        }

        catch

            //檔案不存在

    }