private static void ReportFailure(HttpResponseBase response, int?reportBand, Dictionary <ProtocolUtils.UpdateRequest, string> errors, string message) { if (reportBand == ProtocolUtils.ErrorBand) { response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.MessageBand, ProtocolUtils.DefaultEncoding.GetBytes(string.Format("{0}\n", message)))); foreach (var e in errors) { response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.MessageBand, ProtocolUtils.DefaultEncoding.GetBytes(string.Format("{0} ({1})\n", e.Key.CanonicalName, e.Value ?? "not created, see other errors")))); } response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.ErrorBand, ProtocolUtils.DefaultEncoding.GetBytes("code review creation aborted\n"))); } else { var status = new List <byte[]>(); status.Add(ProtocolUtils.PacketLine(string.Format("unpack {0}\n", message))); foreach (var e in errors) { status.Add(ProtocolUtils.PacketLine(string.Format("ng {0} {1}\n", e.Key.CanonicalName, e.Value ?? "not created, see other errors"))); } status.Add(ProtocolUtils.EndMarker); response.BinaryWrite(ProtocolUtils.Band(reportBand, status)); } }
protected override void WriteFile(HttpResponseBase response) { Grid grid = new Grid(); var properties = _table.Columns; foreach (DataColumn propertyDescriptor in properties) { grid.Columns.Add(new GridColumn(propertyDescriptor.Caption, 80)); } foreach (DataRow item in _table.Rows) { var row = grid.NewRow(); for (int i = 0; i < properties.Count; i++) { var propertyDescriptor = properties[i]; row[i].Text = item[i]; } grid.Rows.Add(row); } ExcelExport export = new ExcelExport(); var bytes = export.Export(grid); response.BinaryWrite(bytes); response.End(); }
/// <summary> /// 重写ExecuteResult /// </summary> /// <param name="context">ControllerContext</param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding == null) { this.ContentEncoding = Encoding.UTF8; } response.ContentEncoding = this.ContentEncoding; if (this.Data != null) { var data = NewtonsoftSerialize(this.Data); byte[] bytes = this.ContentEncoding.GetBytes(data); response.BufferOutput = true; response.AddHeader("Content-Length", bytes.Length.ToString()); response.BinaryWrite(bytes); response.Flush(); response.End(); } }
/// <summary> /// Copies the full binary contents of the given blob to the given HTTP response. /// </summary> private static void CopyContents(CloudBlob blob, HttpResponseBase response, long offset = 0) { blob.FetchAttributes(); response.BufferOutput = false; response.AddHeader("Content-Length", blob.Attributes.Properties.Length.ToString()); response.Flush(); using (var reader = blob.OpenRead()) { reader.Seek(offset, System.IO.SeekOrigin.Begin); byte[] buffer = new byte[1024 * 4]; // 4KB buffer while (reader.CanRead) { int numBytes = reader.Read(buffer, 0, buffer.Length); if (numBytes <= 0) { break; } response.BinaryWrite(buffer); response.Flush(); } } }
private void OutputLine(HttpResponseBase response, object item) { string str = ObjectReflectionHelper.BuildCSVStringFromObject(item, this.Columns); str += Environment.NewLine; response.BinaryWrite(this.ContentEncoding.GetBytes(str)); }
protected override void WriteFile(HttpResponseBase response) { var type = ViewModelDescriptor.GetTypeDescriptor(_itemType); Grid grid = new Grid(); var user = _securityHelper.GetCurrentUser(); var properties = type.Properties.Where(x => x.Show && (user == null || x.Permission.Check(user.CurrentUser))).OrderBy(x => x.Order).ToList(); foreach (var propertyDescriptor in properties) { grid.Columns.Add(new GridColumn(propertyDescriptor.ShortName, 80)); } foreach (var item in _items) { var row = grid.NewRow(); for (int i = 0; i < properties.Count; i++) { var propertyDescriptor = properties[i]; row[i].Text = string.Format(propertyDescriptor.ShortNameFormat, propertyDescriptor.GetValue(item)); } grid.Rows.Add(row); } ExcelExport export = new ExcelExport(); var bytes = export.Export(grid); response.BinaryWrite(bytes); response.End(); }
private void OutputLineFromDataTable(HttpResponseBase response, DataRow dr) { var sOut = new StringBuilder(); int i = 0; foreach (DataColumn c in this.dataTable.Columns) { if (i > 0) { sOut.Append(","); } object oValue = dr[c]; string str = ""; if (c.DataType.Equals(typeof(DateTime)) || c.DataType.Equals(typeof(DateTime?))) { str = ObjectReflectionHelper.GetDateStringForCSV(oValue, c.ColumnName); } else { str = TypeHelper.GetStrTrim(oValue); } //半角カンマは全角カンマに変換する。 str = str.Replace(",", ","); sOut.Append(str); i++; } sOut.AppendLine(); response.BinaryWrite(this.ContentEncoding.GetBytes(sOut.ToString())); }
public async Task Export(String path, Int32 TenantId, Int64 UserId, ExpandoObject prms, HttpResponseBase response) { var rm = await RequestModel.CreateFromBaseUrl(_host, Admin, path); var action = rm.CurrentAction; var export = action.Export; if (export == null) { throw new RequestModelException($"There is no export in '{rm.ModelAction}' action"); } if (prms != null) { prms.Append(action.parameters); prms.SetIfNotExists("Id", action.Id); } IDataModel dm = await _dbContext.LoadModelAsync(action.CurrentSource, action.ExportProcedure, prms); Stream stream = null; var templExpr = export.GetTemplateExpression(); if (!String.IsNullOrEmpty(templExpr)) { var bytes = dm.Eval <Byte[]>(templExpr); if (bytes == null) { throw new RequestModelException($"Template stream not found or its format is invalid. ({templExpr})"); } stream = new MemoryStream(dm.Eval <Byte[]>(templExpr)); } else { var fileName = export.template.AddExtension(export.format.ToString()); var appReader = _host.ApplicationReader; var filePath = appReader.MakeFullPath(action.Path, fileName.RemoveHeadSlash()); if (!appReader.FileExists(filePath)) { throw new FileNotFoundException($"Template file not found. ({fileName})"); } stream = appReader.FileStreamFullPathRO(filePath); } switch (export.format) { case RequestExportFormat.xlsx: using (var rep = new ExcelReportGenerator(stream)) { rep.GenerateReport(dm); Byte[] bytes = File.ReadAllBytes(rep.ResultFile); if (bytes == null || bytes.Length == 0) { throw new RequestModelException("There are no bytes to send"); } SetResponseInfo(response, export); response.BinaryWrite(bytes); stream.Close(); } break; } }
protected override void WriteFile(HttpResponseBase response) { // note: you'll want to handle this better; I'm just choosing a property of each complex type. string[] lines = Data.Select(d => string.Join(", ", d.UserO.UserName, d.ProductO.PName)).ToArray(); byte[] buffer = response.ContentEncoding.GetBytes(string.Join(Environment.NewLine, lines)); response.BinaryWrite(buffer); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } // get rendered HTML from view string html = ViewRenderer.RenderViewToString(context, ViewName, Model); var cssFiles = CssHelper.GetAllCssPaths(html); //html = ClearHtmlStrategy.Clear(html); // generate the PDF content from HTML var pageConfig = PageConfig != null ? PageConfig : PageSize.A4; byte[] content = HtmlToPdfRenderer.Render(html, cssFiles, pageConfig); var contentDisposition = IsAttachment ? "attachement" : "inline"; HttpResponseBase response = context.HttpContext.Response; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.ContentType = "application/pdf"; response.AppendHeader("Content-Disposition", $"{contentDisposition};filename={Filename}.pdf"); response.AddHeader("Content-Length", content.Length.ToString()); response.BinaryWrite(content); response.OutputStream.Flush(); response.OutputStream.Close(); response.End(); }
public static void Generar(LocalReport localReport, string filename, FormatoReporte formato, HttpResponseBase response) { string reportType = formato == FormatoReporte.PDF ? "PDF" : formato == FormatoReporte.EXCEL ? "EXCEL" : "WORD"; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + reportType + "</OutputFormat>" + //" <OutputFormat>PDF</OutputFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; localReport.EnableHyperlinks = true; renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); response.Clear(); response.ContentType = mimeType; response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + fileNameExtension); response.BinaryWrite(renderedBytes); response.End(); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; response.ClearHeaders(); response.AppendHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"); response.AppendHeader("Pragma", "no-cache"); response.AppendHeader("Expires", "-1"); HttpCachePolicyBase cache = response.Cache; cache.SetCacheability(HttpCacheability.NoCache); if (string.IsNullOrEmpty(this.Filename)) { this.Filename = "output.xls"; } response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=" + this.Filename); if (this.ContentEncoding == null) { this.ContentEncoding = System.Text.Encoding.GetEncoding("Shift_JIS"); //this.ContentEncoding = System.Text.Encoding.UTF8; } response.ContentEncoding = this.ContentEncoding; response.BinaryWrite(Data.GetBuffer()); }
public static void ReportExportHelper(LocalReport localReport, string OutputType, string outPutFileName, bool isLandScap, string extension, HttpResponseBase Response) { string reportType = OutputType; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn2.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = ""; if (isLandScap) { deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>8.5in</PageHeight>" + " <MarginTop>0.2in</MarginTop>" + " <MarginLeft>0.2in</MarginLeft>" + " <MarginRight>0.2in</MarginRight>" + " <MarginBottom>0.2in</MarginBottom>" + "</DeviceInfo>"; } else { deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>8.5in</PageHeight>" + " <MarginTop>0.2in</MarginTop>" + " <MarginLeft>0.2in</MarginLeft>" + " <MarginRight>0.2in</MarginRight>" + " <MarginBottom>0.2in</MarginBottom>" + "</DeviceInfo>"; } Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); Response.Clear(); Response.ContentType = mimeType; Response.AddHeader("content-disposition", "attachment; filename=" + outPutFileName + "." + extension); Response.BinaryWrite(renderedBytes); Response.End(); }
/// <summary> /// Writes binary output to the HttpResponse. /// </summary> /// <param name="buffer">The buffer.</param> public void BinaryWrite(byte[] buffer) { if (_context != null) { _context.ContentType = ContentType; _context.BinaryWrite(buffer); } }
protected override void WriteFile(HttpResponseBase response) { // note: implicit UserO.ToString() and ProductO.ToString() usage, // you'll want to handle this better before demoing this concept string[] lines = Data.Select(d => string.Join(", ", d.UserO, d.ProductO)).ToArray(); byte[] buffer = response.ContentEncoding.GetBytes(string.Join(Environment.NewLine, lines)); response.BinaryWrite(buffer); }
private static void ReportSuccess(HttpResponseBase response, int?reportBand) { response.BinaryWrite(ProtocolUtils.Band(reportBand, ProtocolUtils.PacketLine("unpack ok\n"), ProtocolUtils.PacketLine("ok " + DestinationRefName + "\n"), ProtocolUtils.PacketLine("ok " + SourceRefName + "\n"), ProtocolUtils.EndMarker)); }
public static void ToExcel(this HttpResponseBase response, string fileName, MemoryStream ms) { response.ContentType = "application/vnd.ms-excel;charset=utf-8"; response.HeaderEncoding = Encoding.UTF8; response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName) + ".xls"); response.Clear(); response.BinaryWrite(ms.GetBuffer()); response.End(); }
public void CreatePDF(string FileName, string DataSourceName, List <EntityDetallePedido> oDataSource, HttpResponseBase Response) { var oDataSourceNew = oDataSource. Select(n => new { Producto = n.Key.IDProducto.ToString(), PrecioUnitario = "0", Cantidad = n.Cantidad }); ReportDataSource rds = new ReportDataSource(DataSourceName, oDataSourceNew.ToArray()); //ReportExecutionService rsExcel = new ReportExecutionService(); Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; ReportViewer viewer = new ReportViewer(); viewer.ProcessingMode = ProcessingMode.Remote; PermissionSet permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); viewer.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions); Assembly asm = Assembly.Load(Assembly.GetExecutingAssembly().FullName); AssemblyName asm_name = asm.GetName(); viewer.LocalReport.AddFullTrustModuleInSandboxAppDomain(new StrongName(new StrongNamePublicKeyBlob(asm_name.GetPublicKeyToken()), asm_name.Name, asm_name.Version)); viewer.LocalReport.ReportPath = "Reporte/VistaPrevia/" + FileName + ".rdlc"; //List<ReportParameter> lstParameter = new List<ReportParameter>(); //foreach (var item in ArrayReportParameter) //{ // ReportParameter parameter = new ReportParameter(item.Split(',')[0].ToString(), item.Split(',')[1].ToString()); // lstParameter.Add(parameter); //} //if (lstParameter.Count() > 0) // viewer.LocalReport.SetParameters(lstParameter); viewer.LocalReport.DataSources.Add(rds); //byte[] bytes = viewer.LocalReport.Render("Excel",string.Empty, out mimeType, out encoding, out extension, out streamIds, out warnings); byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings); Response.Buffer = true; Response.Clear(); Response.ContentType = mimeType; Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "." + extension); Response.BinaryWrite(bytes); //Response.Flush(); }
/// <summary> /// 根据DataTable生成excel /// </summary> public static void RenderToBrowser(List <DataTable> table, List <string> sheetNames, string fileName, HttpResponseBase response, HttpRequestBase request) { if (request.Browser.Browser == "IE") { fileName = HttpUtility.UrlEncode(fileName); } response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xls"); response.BinaryWrite(RenderToExcel(table, sheetNames).ToArray()); }
private static void SaveToResponse(string fileName, HttpResponseBase stream) { using (var reader = File.OpenRead(fileName)) { var bt = new byte[1024]; var count = 0; while ((count = reader.Read(bt, 0, 1024)) == 1024) { stream.BinaryWrite(bt); } if (count > 0) { var bt2 = new byte[count]; Array.Copy(bt, bt2, count); stream.BinaryWrite(bt2); } } }
private void AddResponseHeader(HttpResponseBase Response) { Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=" + GetExcelName()); Response.ContentType = "application/ms-excel"; Response.Charset = Encoding.UTF8.EncodingName; Response.ContentEncoding = Encoding.Unicode; Response.BinaryWrite(Encoding.Unicode.GetPreamble()); }
private void GenerateThumbnailFromStream(Stream imgStream, HttpResponseBase Response, string imgExt) { if (imgStream == null) { return; } var imgFull = Image.FromStream(imgStream); imgStream.Close(); imgStream.Dispose(); var curHeight = imgFull.Height; var curWidth = imgFull.Width; imgHeight = curHeight; imgWidth = curWidth; if (imgMaxHeight.HasValue || imgMaxWidth.HasValue) { if (curHeight > imgMaxHeight || curWidth > imgMaxWidth) { if (imgMaxHeight.HasValue && imgMaxWidth.HasValue) { if (imgMaxHeight > imgMaxWidth) { imgHeight = (imgMaxWidth.Value * curHeight) / curWidth; imgWidth = imgMaxWidth.Value; } else { imgWidth = (imgMaxHeight.Value * curWidth) / curHeight; imgHeight = imgMaxHeight.Value; } } else if (imgMaxHeight.HasValue) { imgWidth = (imgMaxHeight.Value * curWidth) / curHeight; imgHeight = imgMaxHeight.Value; } else { imgHeight = (imgMaxWidth.Value * curHeight) / curWidth; imgWidth = imgMaxWidth.Value; } } } var img = GenerateThumbnail(imgFull, imgExt); Response.Clear(); Response.ContentType = "image/" + (imgExt.Length >= 4 ? imgExt.Substring(1) : "png"); Response.BinaryWrite(img); Response.End(); }
public static void CreateExcelResponse(HttpResponseBase response, ExcelPackage excelPackage, string worksheetName) { if (Path.GetExtension(worksheetName) != ".xlsx") { worksheetName = string.Format("{0}.xlsx", worksheetName); } response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("content-disposition", string.Format("attachment; filename={0}", worksheetName)); response.BinaryWrite(excelPackage.GetAsByteArray()); response.End(); }
public static void Export <T>(List <T> data, HttpResponseBase response, string excelName) { Workbook workbook = new Workbook(); Worksheet sheet = (Worksheet)workbook.Worksheets[0]; //为标题设置样式 Style styleTitle = workbook.Styles[workbook.Styles.Add()]; //新增样式 styleTitle.HorizontalAlignment = TextAlignmentType.Center; //文字居中 styleTitle.Font.Name = "宋体"; //文字字体 styleTitle.Font.Size = 18; //文字大小 styleTitle.Font.IsBold = true; //粗体 var objType = typeof(T); PropertyInfo[] properties = objType.GetProperties(); //生成行1 标题行 sheet.Cells.Merge(0, 0, 1, properties.Length); //合并单元格 sheet.Cells[0, 0].PutValue(excelName); //填写内容 sheet.Cells[0, 0].SetStyle(styleTitle); sheet.Cells.SetRowHeight(0, 20); int i = 2; int j = 0; foreach (PropertyInfo propInfo in properties) { var attrName = propInfo.Name; DescriptionAttribute attr = (DescriptionAttribute)Attribute.GetCustomAttribute(propInfo, typeof(DescriptionAttribute)); if (attr != null) { attrName = attr.Description; sheet.Cells[i, j].PutValue(attrName); int ii = i + 1; foreach (var d in data) { sheet.Cells[ii, j].PutValue(propInfo.GetValue(d, null)); ii++; } sheet.Cells.SetColumnWidth(j, 15); j++; } } response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", excelName)); response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/ms-excel"; response.BinaryWrite(workbook.SaveToStream().ToArray()); response.End(); }
async Task DownloadImpl(String Base, String id, Boolean raw, HttpResponseBase Response, Action <ExpandoObject> setParams, String suffix, String token) { try { var url = $"/_attachment{Base}/{id}"; var ai = await _baseController.DownloadAttachment(url, setParams, suffix); if (ai == null) { throw new RequestModelException($"Attachment not found. (Id:{id})"); } if (!_baseController.IsTokenValid(Response, ai.Token, token)) { return; } if (raw) { Response.ContentType = "application/octet-stream"; } else { Response.ContentType = raw ? "application/octet-stream" : ai.Mime; String repName = ai.Name; if (String.IsNullOrEmpty(repName)) { repName = "Attachment"; } var cdh = new ContentDispositionHeaderValue("attachment") { FileNameStar = _baseController.Localize(repName) + Mime2Extension(ai.Mime) }; Response.Headers.Add("Content-Disposition", cdh.ToString()); } if (ai.Stream != null) { Response.BinaryWrite(ai.Stream); } } catch (Exception ex) { if (raw) { _baseController.WriteExceptionStatus(ex, Response); } else { _baseController.WriteHtmlException(ex, Response.Output); } } }
private void OutputHeader(HttpResponseBase response) { if (this.Data.Count == 0) { return; } var target = this.Data[0]; string str = ObjectReflectionHelper.BuildCSVHeaderStringFromObject(target, this.Columns, this.Titles); str += Environment.NewLine; response.BinaryWrite(this.ContentEncoding.GetBytes(str)); }
private static void OutputFile(HttpResponseBase response, System.IO.FileInfo fileInfo, byte[] content) { if (content != null) { response.BinaryWrite(content); } else { response.WriteFile(fileInfo.FullName, 0, fileInfo.Length); } response.Flush(); response.End(); }
/// <summary> /// 导出 /// </summary> public void DoExport() { if (this.FileName == null) { this.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); } Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.{1}", FileName, FileExt)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ExcleExporter.Book.Write(ms); if (FileExt.Substring(0, 1) == ".") { FileExt = FileExt.Substring(1); } if (FileExt.ToLower() == "zip") { var path = Server.MapPath("~/Exports/"); Utils.CreateFolderIfNeeded(path); if (System.IO.File.Exists(path + FileName + ".xls")) { System.IO.File.Delete(path + FileName + ".xls"); } using (var fileStream = new System.IO.FileStream(path + FileName + ".xls", System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite)) { ms.Position = 0; ms.CopyTo(fileStream); // fileStream is not populated } this.Files.Add(path + FileName + ".xls"); if (System.IO.File.Exists(path + FileName + ".zip")) { System.IO.File.Delete(path + FileName + ".zip"); } ZipHelper.Zip(this.Files.ToArray(), path + FileName + ".zip"); Response.WriteFile(path + FileName + ".zip"); } else { Response.BinaryWrite(ms.ToArray()); } ExcleExporter.Book = null; ms.Close(); ms.Dispose(); }
private void Export(PageFreshnessReportViewModel model, HttpResponseBase response) { using (var package = new ExcelPackage()) { AddWorksheet(package, "Top10FreshestPages", model.Top10FreshestPages); AddWorksheet(package, "Top10LeastFreshPages", model.Top10LeastFreshPages); response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("content-disposition", string.Format("attachment; filename=pages{0}.xlsx", DateTime.Now.ToString("yyyyMMdd"))); response.BinaryWrite(package.GetAsByteArray()); response.Flush(); response.End(); } }
/// <summary> /// 下载文件 /// </summary> /// <param name="context">HttpContext</param> /// <param name="filePath">要下载的文件的完整路径</param> /// <param name="downloadName">下载时要显示的文件名</param> /// <param name="isDelete">下载后是否删除文件</param> /// <param name="bts">文件的byte</param> public void FileDonwLoad(HttpRequestBase Request, HttpResponseBase Response, string downloadName, bool isDelete = false, byte[] bts = null, string filePath = null) { //以字符流的形式下载文件 byte[] bytes; if (bts == null) { FileStream fs = new FileStream(filePath, FileMode.Open); bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); //读取完成后删除 if (isDelete) { File.Delete(filePath); } } else { bytes = bts; } //下载文件 Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8"); if (!string.IsNullOrEmpty(filePath) && filePath.Contains(".xls")) { Response.ContentType = "application/ms-excel"; } else { Response.ContentType = "application/octet-stream"; } if (Request.UserAgent.ToLower().IndexOf("msie") > -1) { downloadName = HttpUtility.UrlPathEncode(downloadName); } if (Request.UserAgent.ToLower().IndexOf("firefox") > -1) { Response.AddHeader("Content-Disposition", "attachment;filename=\"" + downloadName + "\""); } else { Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName); } Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.BinaryWrite(bytes); Response.Flush(); //context.Response.End(); //清空以免缓存影响下次下载 Response.Clear(); }