博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
asp.net 下载文件
阅读量:4945 次
发布时间:2019-06-11

本文共 10664 字,大约阅读时间需要 35 分钟。

第一种下载方法

private void DownExcel(string filePath)        {            //string path = HttpContext.Current.Server.MapPath("/UploadFiles/KGData/test.xls");string path = HttpContext.Current.Server.MapPath(filePath);            FileInfo fileInfo = new FileInfo(filePath);            Response.Clear();            Response.ClearContent();            Response.ClearHeaders();            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);            Response.AddHeader("Content-Length", fileInfo.Length.ToString());            Response.AddHeader("Content-Transfer-Encoding", "binary");            Response.ContentType = "application/octet-stream";            Response.ContentEncoding = Encoding.GetEncoding("gb2312");            Response.WriteFile(fileInfo.FullName);            Response.Flush();            Response.End();                     }
View Code

第二种方法

windows.location.href = "/test/ExcelDownLoad.aspx?file=test.xls" ;

protected void ResponseFile()        {           string fileName = Request.QueryString["file"];           ext(fileName);            System.IO.Stream iStream = null;            // 缓冲区为10k            byte[] buffer = new Byte[10240];            // 文件长度            int length;            // 需要读的数据长度            long dataToRead;            try            {                string fileName = path;                string filepath = HttpContext.Current.Server.MapPath("/ExcelTemp/") + fileName; //待下载的文件路径                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,                    System.IO.FileAccess.Read, System.IO.FileShare.Read);                Response.Clear();                dataToRead = iStream.Length;                //iStream.Position = 0;                long p = 0;                if (Request.Headers["Range"] != null)                {                    Response.StatusCode = 206;                    p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));                }                if (p != 0)                {                    Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());                }                Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());                Response.ContentType = "application/octet-stream";                Response.AddHeader("Content-Disposition", "attachment; filename=" +HttpUtility.UrlEncode(Path.GetFileName(filepath)));                Response.AppendHeader("Location", Request.Url.AbsoluteUri);                 iStream.Position = p;                dataToRead = dataToRead - p;                while (dataToRead > 0)                {    // 检查客户端是否还处于连接状态                    if (Response.IsClientConnected)                    {                        length = iStream.Read(buffer, 0, 10240);                        Response.OutputStream.Write(buffer, 0, length);                                             Response.Flush();                                                buffer = new Byte[10240];                        dataToRead = dataToRead - length;                    }                    else                    {    // 如果不再连接则跳出死循环                        dataToRead = -1;                    }                }            }            catch (Exception ex)            {                Response.Write("Error : 文件不存在!!!");               // Response.Redirect("../Supplier_Idex.aspx");            }            finally            {                if (iStream != null)                {                    iStream.Close();                }                Response.End();            }        }
View Code

 

protected string ext(string file)        {            string str = string.Empty;            if(!string.IsNullOrEmpty(file))            {                var invalidPattern = new Regex(@"[\\\/\:\*\?<\>\|]");                string strExt = invalidPattern.Replace(file, "");                strExt =  Path.GetExtension(file);                switch(strExt)                {                    case ".config":                        str = "文件不存在";                        break;                    default:                        str = file; break;                }            }            return str;        }
View Code

 

 

使用jquery下载方法

js方法

jQuery.download = function (downloadurl, method, filepath, filename) {            jQuery('
' + // action请求路径及推送方法 '
' + // 文件路径 '
' + // 文件名称 '
') .appendTo('body').submit().remove(); }; function ExportToExcel() { if (confirm("确定要导出Excel吗?")) { var start = getQueryString('fromDate'); var end = getQueryString('toDate'); var brand = getQueryString('brandCompany'); var staff = getQueryString('staff'); var groupName = getQueryString('groupName'); $.ajax({ type: "POST", dataType: "json", url: "Test.aspx/ExportToExcel", data: "{fromDate:'" + start + "',toDate:'" + end + "',brandName:'" + brand + "'}", contentType: "application/json; charset=utf-8", success: function (data) { var result = eval('(' + data.d + ')'); if (result.Body == '没有需要导出的信息') { alert(result.Body); } else { $.download(result.DownLoadUrl, 'post', result.FilePath, result.FileName); } }, error: function (msg) { alert('系统繁忙,请稍后重试!'); } }); } }function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var result = window.location.search.substr(1).match(reg); if (result != null) { return unescape(result[2]); } else { return null; } }

 

后台方法

[WebMethod]        public static string ExportToRiskExcel(DateTime fromDate,DateTime toDate,string brandName)        {            DataSet ds = new wcfInternalService.InternalServiceClient().GetList(fromDate, toDate, brandName);            DownResult result = new DownResult()            {                Success = false,                Body = "导出失败,请稍后再试!"            };            if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)            {                string[] columns = { "序号", "案件", "车牌", "分类", "处理时间", "人员", "金额" };                result = ExportExcel(ds.Tables[0], columns, "分布详情", result);            }            else            {                result = new DownResult()                {                    Success = true,                    Body = "没有需要导出的信息"                };            }            return JsonConvert.SerializeObject(result);        }public static DownResult ExportExcel(DataTable dt, string[] columns, string sheetName, DownResult result)        {            string filePath = string.Empty;//文件路径            string fileName = string.Empty;//文件名称            Stream stream = DataTableToExcel(dt, columns, sheetName);            ExcelPackage package = new ExcelPackage(stream);            fileName = sheetName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";            filePath = HttpContext.Current.Server.MapPath("~/UploadFile/");//文件保存地址              if (!Directory.Exists(filePath))//如果不存在就创建file文件夹            {                Directory.CreateDirectory(filePath);            }            package.SaveAs(new FileInfo(filePath + fileName));            result = new DownResult()            {                Success = true,                Body = "导出成功!",                DownLoadUrl = "DownExcel.aspx",                FilePath = filePath,                FileName = fileName,            };            return result;        }      public static Stream DataTableToExcel(DataTable dataTable, string[] columns, string sheetName)        {            try            {                using (ExcelPackage pck = new ExcelPackage())                {                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add(sheetName);                    ws.Cells["A1"].LoadFromDataTable(dataTable, true);                    for (int i = 1; i <= columns.Length; i++)                    {                        using (ExcelRange rng = ws.Cells[1, i])                        {                            rng.Style.Font.Bold = true;                            rng.Value = columns[i - 1];                        }                    }                    MemoryStream ms = new MemoryStream();                    pck.SaveAs(ms);                    ms.Flush();                    ms.Position = 0;//指定当前流的位置从0开始                    return ms;                }            }            catch (Exception ex)            {                throw ex;            }        } public class DownResult    {        public bool Success { get; set; }        public string Body { get; set; }        public string DownLoadUrl { get; set; }        public string FilePath { get; set; }        public string FileName { get; set; }    }

 方法必须为静态,参数需要一致

 下载页面方法

protected void Page_Load(object sender, EventArgs e)        {            string fileName = Request["filename"];//下载文档名              string filePath = Request["filepath"];            FileInfo fileInfo = new FileInfo(filePath + fileName);            Response.Clear();            Response.ClearContent();            Response.ClearHeaders();            String userAgent = HttpContext.Current.Request.UserAgent;            //判断是否为ie10以下及ie11浏览器              if (userAgent.Contains("MSIE") || userAgent.Contains("rv:11"))            {                fileName = HttpUtility.UrlEncode(fileName);            }            Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fileName));            Response.AddHeader("Content-Length", fileInfo.Length.ToString());            Response.AddHeader("Content-Transfer-Encoding", "binary");            Response.ContentType = "application/octet-stream";            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");            Response.WriteFile(fileInfo.FullName);            Response.Flush();            if (File.Exists(Path.GetFullPath(fileInfo.ToString())))            {                File.Delete(Path.GetFullPath(fileInfo.ToString()));//用户下载后删除服务器文件            }            Response.End();        }
View Code

 

转载于:https://www.cnblogs.com/ZJ199012/p/6293050.html

你可能感兴趣的文章
C#操作目录和文件
查看>>
警惕数组的浅拷贝
查看>>
百度地图 导航
查看>>
SQLServer 错误: 15404,无法获取有关 Windows NT 组
查看>>
html5全局属性
查看>>
【转】Android Hook框架Xposed详解
查看>>
Android 有用代码片段总结
查看>>
英语各种时态例句
查看>>
从下往上看--新皮层资料的读后感 第三部分 70年前的逆向推演- 从NN到ANN
查看>>
(转)系统引导管理器GRUB详解
查看>>
数据访问C#入门经典第21章-读写压缩数据
查看>>
PHP超时处理全面总结(转)
查看>>
利用python进行数据分析--pandas入门2
查看>>
[zz]使用 libevent 和 libev 提高网络应用性能
查看>>
Linux故障处理最佳实践
查看>>
6标准文件读写
查看>>
jsTree 核心功能(core functionality) API
查看>>
Perl oop链接数据库
查看>>
网络虚拟化我眼中的OpenFlow
查看>>
[leetcode] 3. Longest Substring Without Repeating Characters
查看>>