Web下載文件(導(dǎo)出)

MVC 實現(xiàn)將數(shù)據(jù)庫的內(nèi)容(查詢結(jié)果導(dǎo)出)

1 (以流的形式返回給前端,導(dǎo)出文件),文件內(nèi)容是動態(tài)查詢生成的

1.1數(shù)據(jù)處理

        /// <summary>
        ///  輸出硬盤文件,提供下載 支持大文件、續(xù)傳、速度限制、資nse, string _fileName, StringBuilder data, long _speed)
        {
            try源占用小
        /// </summary>
        /// <param name="_Request">Page.Request對象</param>
        /// <param name="_Response">Page.Response對象</param>
        /// <param name="_fileName">下載文件名</param>
        /// <param name="_data">數(shù)據(jù)(可變字符串)</param>
        /// <param name="_speed">每秒允許下載的字節(jié)數(shù)</param>
        /// <returns>返回是否成功</returns>
        public static bool ResponseFile(HttpRequestBase _Request, HttpResponseBase _Response, string _fileName, StringBuilder data, long _speed)
        {
            try
            {
                //用BinaryReader 讀取某個路徑下的文件流
                //FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                // BinaryReader br = new BinaryReader(myFile);
               //用BinaryReader讀取字節(jié)數(shù)組
                StringBuilder strbData = new StringBuilder();
               // byte[] shuzu = Encoding.Unicode.GetBytes(data.ToString());
               ##byte[] shuzu = Encoding.UTF8.GetBytes(data.ToString()); //替換上面的(解決導(dǎo)出csv文件表頭 中文亂碼的問題)**
                MemoryStream myData = new MemoryStream(shuzu);
                BinaryReader br = new BinaryReader(myData);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    //long fileLength = myFile.Length;
                    long fileLength = myData.Length;
                    long startBytes = 0;
                    int pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.Charset = "gb2312";
                    _Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName + ".csv", System.Text.Encoding.GetEncoding("gb2312")));
                    _Response.HeaderEncoding = System.Text.Encoding.GetEncoding("gb2312");//表頭添加編碼格式

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myData.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

1.2 Controller層

[HttpGet]
        public ActionResult ExportCard(string customerId,string contractId,string fileName)
        {

            CardModel cardModel = new CardModel();
            List<Card> listData= cardModel.GetByInfo(customerId,contractId);
            StringBuilder strData = new StringBuilder();

            try
            {
                strData.Append("序號"+",");
                strData.Append("WTP號" + ",");
                strData.Append("CardId");
                strData.Append("\n");
                int i=0;
                foreach (var item in listData)
                {
                    strData.Append(i++);
                    strData.Append(",");
                    strData.Append(item.Code+",");
                    strData.Append(item.CardId);
                    strData.Append("\n");
                }

                bool flag = ImportExport.ResponseFile(Request, Response, fileName, strData,1024000);

                if (true)
                {
                    return Json(new { Success = true, Message = "導(dǎo)入成功!" });
                }
                else
                {
                    return Json(new { Success = false, Message = "導(dǎo)入失敗!" });
                }

            }
            catch (Exception ex)
            {
                ServiceGlobal.CallInLog.Error(string.Format("ResponseError: {0}",ex.Message));
                return Json(new { Success = false, Message = "導(dǎo)入失?。? });
            }
        }

1.3前端代碼

 location.href = "@Url.Action("ExportCard", "Card")" + "?" + "customerId=" + $("#CardCustomerId").val() + "&contractId=" + $("#ContractId").val() + "&fileName=" + $("#fileName").val();
或
var url="@Url.Action("ExportCard", "Card")" + "?" + "customerId=" + $("#CardCustomerId").val() + "&contractId=" + $("#ContractId").val() + "&fileName=" + $("#fileName").val();

            var alink = document.createElement("a");
            alink.download = $("#fileName").val();
            alink.style.display = "none";
            alink.href = url;
            document.body.appendChild(alink);
            alink.click();
            document.body.removeChild(alink);

            $('#myModal').modal('hide'); //彈出框dilog

2 <a>標(biāo)簽下載文件

下載的文件是在服務(wù)器端指定目錄下(靜態(tài)文件),也可以接受后端返回的文件流

創(chuàng)建a標(biāo)簽訪問
<a href="后端接口地址"、url>下載文件</a>
觸發(fā)a的click事件

3 form表單提交下載

form表單提交,接受后端返回的文件流

參考:

Web端下載文件的幾種方式
[http://www.itdecent.cn/p/bf0a4e3926a4]

前端接收文件流 并 下載的幾種方式
[https://blog.csdn.net/weixin_33910385/article/details/88702258]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,621評論 1 32
  • ¥開啟¥ 【iAPP實現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,295評論 0 17
  • 冬季的傍晚,暮色蒼涼,夕陽,把幾只鴉雀匆匆趕回了歸巢,夜,已經(jīng)加快了腳步……而我,接上放學(xué)的兒子,剛剛駕車路...
    伊麗蘇白閱讀 184評論 0 1

友情鏈接更多精彩內(nèi)容