Web下载文件(导出)

MVC 实现将数据库的内容(查询结果导出)

1 (以流的形式返回给前端,导出文件),文件内容是动态查询生成的

1.1数据处理

        /// <summary>
        ///  输出硬盘文件,提供下载 支持大文件、续传、速度限制、资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">数据(可变字符串)</param>
        /// <param name="_speed">每秒允许下载的字节数</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读取字节数组
                StringBuilder strbData = new StringBuilder();
               // byte[] shuzu = Encoding.Unicode.GetBytes(data.ToString());
               ##byte[] shuzu = Encoding.UTF8.GetBytes(data.ToString()); //替换上面的(解决导出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 = "导入成功!" });
                }
                else
                {
                    return Json(new { Success = false, Message = "导入失败!" });
                }

            }
            catch (Exception ex)
            {
                ServiceGlobal.CallInLog.Error(string.Format("ResponseError: {0}",ex.Message));
                return Json(new { Success = false, Message = "导入失败!" });
            }
        }

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>标签下载文件

下载的文件是在服务器端指定目录下(静态文件),也可以接受后端返回的文件流

创建a标签访问
<a href="后端接口地址"、url>下载文件</a>
触发a的click事件

3 form表单提交下载

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

参考:

Web端下载文件的几种方式
[https://www.jianshu.com/p/bf0a4e3926a4]

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,887评论 1 32
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,882评论 0 17
  • 冬季的傍晚,暮色苍凉,夕阳,把几只鸦雀匆匆赶回了归巢,夜,已经加快了脚步……而我,接上放学的儿子,刚刚驾车路...
    伊丽苏白阅读 1,360评论 0 1

友情链接更多精彩内容