1. 程式人生 > >C#(伺服器端)通過檔案流下載日誌檔案

C#(伺服器端)通過檔案流下載日誌檔案

C#(伺服器端)通過檔案流下載日誌檔案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using xL.WAF;
using Nestle.Import.WebApi.Code;
using System.IO;
using System.Text;

namespace Nestle.Import.WebApi.Controller
{
    [WebApi]
    [Alias("Downlog")]
    [Auth]
    public class logController : BaseController
    {
        /// <summary>
        /// 通過檔案流下載日誌檔案
        /// </summary>
        ///<remarks>2018-12-24</remarks>
        [Action]
        public string download_log(){
            string relativePath = HttpRuntime.AppDomainAppPath.ToString();//獲取相對路徑
            string sFileName = "Log_" + DateTime.Now.ToString("yyyy-MM-dd") + "_log_INFO.txt";
            string FileNamePath = relativePath + "logs\\" + sFileName; //檔案的絕對路徑
                string filePath = FileNamePath;
                FileInfo fileInfo = new FileInfo(filePath);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sFileName);//下載後的檔案命名
                HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.WriteFile(fileInfo.FullName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            return "檔案已下載成功!";
        }
    }
}