private static Stream PrepareImageStream(string fileName, string mime) { System.Web.HttpResponse stream = System.Web.HttpContext.Current.Response; stream.Clear(); stream.ClearContent(); stream.ClearHeaders(); stream.ContentType = mime; stream.AddHeader("Content-Disposition", "inline;filename=" + fileName); return(stream.OutputStream); }
// SetsResponse header and cache public void SetupResponse(System.Web.HttpResponse response, string fileName) { response.ClearHeaders(); response.Clear(); response.Cache.SetCacheability(System.Web.HttpCacheability.Private); response.Cache.SetMaxAge(new TimeSpan(0)); response.Cache.SetExpires(new DateTime(0)); response.Cache.SetNoServerCaching(); response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (fileName + "\""))); }
internal static void CreatePDFDocument(DataTable dt, string excelFilename, System.Web.HttpResponse Response) { // // For PDF export we are using the free open-source iTextSharp library. // Document pdfDoc = new Document(); MemoryStream pdfStream = new MemoryStream(); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream); pdfDoc.Open();//Open Document to write pdfDoc.NewPage(); iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7); PdfPTable PdfTable = new PdfPTable(dt.Columns.Count); PdfPCell PdfPCell = null; //Add Header of the pdf table for (int column = 0; column < dt.Columns.Count; column++) { PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8))); PdfTable.AddCell(PdfPCell); } //How add the data from datatable to pdf table for (int rows = 0; rows < dt.Rows.Count; rows++) { for (int column = 0; column < dt.Columns.Count; column++) { PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); PdfTable.AddCell(PdfPCell); } } PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table pdfDoc.Add(PdfTable); // add pdf table to the document pdfDoc.Close(); pdfWriter.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + excelFilename); Response.BinaryWrite(pdfStream.ToArray()); Response.End(); }
} // TODO: Add constructor logic here public void ProcessRequest(System.Web.HttpContext context) { System.Web.HttpResponse response = context.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/html"; response.ContentEncoding = System.Text.Encoding.UTF8; // <p id="errorMessage">@error.Type: @error.Message</p> // <span>@error.StackTrace</span> string res = ResourceHelper.GetResource(typeof(ErrorTemplateHandler), "ErrorTemplate.htm"); response.Write(res); // response.Write("<html><body><h1>Hello 15Seconds Reader "); // response.Write("</body></html>"); } // End Sub ProcessRequest
public JObject DownloadFile(string fileName) { JObject obj = new JObject(); try { System.Web.HttpRequest httpRequest = System.Web.HttpContext.Current.Request; string filePath = System.Web.HttpContext.Current.Server.MapPath("~/ApiUploadFile/"); filePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/ApiUploadFile/"), fileName); if (File.Exists(filePath)) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.ClearHeaders(); response.ClearContent(); response.Buffer = true; response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName)); response.Charset = "utf-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); response.ContentType = System.Web.MimeMapping.GetMimeMapping(fileName); response.WriteFile(filePath); response.Flush(); response.Close(); obj.Add("success", true); obj.Add("message", ""); } else { obj.Add("success", false); obj.Add("message", "文件不存在!"); } } catch (Exception ex) { obj.Add("success", false); obj.Add("message", ex.Message); } return(obj); }
/// <summary> /// Handles the Click event of the btnDownloadLog control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDownloadLog_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("content-disposition", "attachment; filename=slingshot-errors.log"); response.Charset = ""; string filePath = Server.MapPath("~/App_Data/SlingshotFiles/slingshot-errors.log"); if (File.Exists(filePath)) { response.TransmitFile(filePath); } response.Flush(); response.End(); response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); }
public static void Export(System.Data.DataTable dt, System.Web.HttpResponse response, string filename) { //first let's clean up the response.object response.Clear(); response.ClearHeaders(); response.Buffer = true; response.ContentEncoding = System.Text.Encoding.UTF8; response.Charset = "utf-8"; response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; // added to help issue with IE problems with Cache-Control: no-cache response.ExpiresAbsolute = DateTime.Now.AddYears(-1); //header/footer to support UTF-8 characters var header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + Constants.vbLf + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + Constants.vbLf + "<head>" + Constants.vbLf + "<title></title>" + Constants.vbLf + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + Constants.vbLf + "<style>" + Constants.vbLf + "</style>" + Constants.vbLf + "</head>" + Constants.vbLf + "<body>" + Constants.vbLf; var footer = Constants.vbLf + "</body>" + Constants.vbLf + "</html>"; response.Write(header); //create an htmltextwriter which uses the stringwriter var htmlWrite = new System.Web.UI.HtmlTextWriter(response.Output); //instantiate a datagrid var dg = new System.Web.UI.WebControls.DataGrid(); //set the datagrid datasource to the dataset passed in dg.DataSource = dt; //bind the datagrid dg.DataBind(); //tell the datagrid to render itself to our htmltextwriter dg.RenderControl(htmlWrite); response.Write(footer); //all that's left is to output the html response.End(); }
public void Save(System.IO.Stream OutputStream, System.Web.HttpResponse response) { string filename = "Export_" + Guid.NewGuid().ToString(); string completePathOne = GenerateUniquePath(filename, "xlsx"); string completePathTwo = GenerateUniquePath(filename, "xls"); string completePath = null; string tableName = null; ISDWorksheet ws = (ISDWorksheet)this.Worksheets[0]; ISDTable ta = ws.Table; tableName = ws.Name; ArrayList rows = ta.Rows; ISDWorksheetRow row0 = null; if (rows.Count > 0) { row0 = (ISDWorksheetRow)rows[0]; } ISDWorksheetRow row1 = row0; if (rows.Count > 1) { row1 = (ISDWorksheetRow)rows[1]; } ArrayList cols = ta.Columns; string colDefs = GetColumnDefinitions(cols, row0.Cells, row1.Cells, true); string colNames = GetColumnDefinitions(cols, row0.Cells, row1.Cells, false); completePath = completePathTwo; HSSFWorkbook hssfwb = new HSSFWorkbook(); IDataFormat format = hssfwb.CreateDataFormat(); ISheet sh = hssfwb.CreateSheet("Sheet1"); int rIndex = 0; IRow r = sh.CreateRow(rIndex); int c = 0; HSSFCellStyle[] styles = new HSSFCellStyle[row0.Cells.Count + 1]; foreach (ISDWorksheetCell hCell in row0.Cells) { HSSFCellStyle style = (HSSFCellStyle)hssfwb.CreateCellStyle(); ICell ce = r.CreateCell(c); ce.SetCellValue(hCell.Text); style.WrapText = true; styles[c] = (HSSFCellStyle)hssfwb.CreateCellStyle(); ce.CellStyle = style; c += 1; } for (rIndex = 1; rIndex <= rows.Count - 1; rIndex++) { ISDWorksheetRow currentRow = (ISDWorksheetRow)rows[rIndex]; r = sh.CreateRow(rIndex); c = 0; for (int i = 0; i <= currentRow.Cells.Count - 1; i++) { //myValue = myValue.Replace("$", "").Replace(",", "") ICell ce = r.CreateCell(c); HSSFCellStyle style = styles[i]; ISDWorksheetCell dCell = (ISDWorksheetCell)currentRow.Cells[i]; string formatStr = dCell.Format; if (dCell.Type == ISDDataType.ISDInteger || dCell.Type == ISDDataType.ISDNumber) { ce.SetCellType(CellType.NUMERIC); if (dCell.Value != null) { ce.SetCellValue(Convert.ToDouble(dCell.Value)); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { System.Globalization.NumberFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; if (string.IsNullOrEmpty(dCell.Format) || dCell.Format == null) { formatStr = "##0.00"; } else if (dCell.Format.Contains("C") || dCell.Format.Contains("c")) { formatStr = info.CurrencySymbol + "##0.00"; } else if (dCell.Format.Contains("P") || dCell.Format.Contains("p")) { formatStr = "##0.00" + info.PercentSymbol; } else if (dCell.Format.Contains(info.CurrencySymbol) || dCell.Format.Contains(info.PercentSymbol)) { // use the user given display format } else { formatStr = "##0.00"; } style.DataFormat = format.GetFormat(formatStr); } } else if (dCell.Type == ISDDataType.ISDDateTime) { if (dCell.Value != null) { ce.SetCellType(CellType.NUMERIC); ce.SetCellValue(Convert.ToDateTime(dCell.Value)); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { System.Globalization.DateTimeFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat; // convert the date format understood by Excel // see http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx switch (dCell.Format) { case "d": formatStr = info.ShortDatePattern; break; case "D": formatStr = info.LongDatePattern; break; case "t": formatStr = info.ShortTimePattern; break; case "T": formatStr = info.LongTimePattern; break; case "f": formatStr = info.LongDatePattern + " " + info.ShortTimePattern; break; case "F": formatStr = info.FullDateTimePattern; break; case "g": formatStr = info.ShortDatePattern + " " + info.ShortTimePattern; break; case "G": formatStr = info.ShortDatePattern + " " + info.LongTimePattern; break; case "M": case "m": formatStr = info.MonthDayPattern; break; case "R": case "r": formatStr = info.RFC1123Pattern; break; case "s": formatStr = info.SortableDateTimePattern; break; case "u": formatStr = info.UniversalSortableDateTimePattern; break; case "U": formatStr = info.FullDateTimePattern; break; case "Y": case "y": formatStr = info.YearMonthPattern; break; default: formatStr = info.ShortDatePattern; break; } // some pattern above might return t but this is not recognized by Excel, so remove it formatStr = formatStr.Replace("t", ""); style.DataFormat = format.GetFormat(formatStr); } } else { ce.SetCellType(CellType.STRING); if (dCell.Value != null) { string myValue = dCell.Text; if (myValue.Length > 255) { myValue = myValue.Substring(0, 255); } ce.SetCellValue(myValue); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { style.DataFormat = HSSFDataFormat.GetBuiltinFormat("TEXT"); style.WrapText = true; } } ce.CellStyle = style; c += 1; } } MemoryStream ms = new MemoryStream(); hssfwb.Write(ms); string NPOIDownloadFileName = this.Properties.Title; if (completePath.EndsWith(".xlsx")) { NPOIDownloadFileName += ".xlsx"; } else { NPOIDownloadFileName += ".xls"; } response.ClearHeaders(); response.Clear(); response.Cache.SetCacheability(System.Web.HttpCacheability.Private); response.Cache.SetMaxAge(new TimeSpan(0)); response.Cache.SetExpires(new DateTime(0)); response.Cache.SetNoServerCaching(); response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (NPOIDownloadFileName + "\""))); response.ContentType = "application/vnd.ms-excel"; OutputStream.Write(ms.ToArray(), 0, ms.ToArray().Length); return; }
} // TODO: Add constructor logic here public void ProcessRequest(System.Web.HttpContext context) { System.Web.HttpResponse response = context.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/html"; response.ContentEncoding = System.Text.Encoding.UTF8; string html = @"<!DOCTYPE html> <html xmlns=""http://www.w3.org/1999/xhtml"" lang=""en""> <head> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge,chrome=1"" /> <meta http-equiv=""cache-control"" content=""max-age=0"" /> <meta http-equiv=""cache-control"" content=""no-cache"" /> <meta http-equiv=""expires"" content=""0"" /> <meta http-equiv=""expires"" content=""Tue, 01 Jan 1980 1:00:00 GMT"" /> <meta http-equiv=""pragma"" content=""no-cache"" /> <meta charset=""utf-8"" /> <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /> <meta http-equiv=""Content-Language"" content=""en"" /> <meta name=""viewport"" content=""width=device-width,initial-scale=1"" /> <!-- <meta name=""author"" content=""name"" /> <meta name=""description"" content=""description here"" /> <meta name=""keywords"" content=""keywords,here"" /> <link rel=""shortcut icon"" href=""favicon.ico"" type=""image/vnd.microsoft.icon"" /> <link rel=""stylesheet"" href=""stylesheet.css"" type=""text/css"" /> --> <title>Title</title> <style type=""text/css"" media=""all""> body { background-color: #0c70b4; color: #546775; font: normal 400 18px ""PT Sans"", sans-serif; -webkit-font-smoothing: antialiased; } </style> <script type=""text/javascript""> </script> </head> <body> <h1>Hello 15Seconds Reader</h1> </body> </html> "; html = ResourceHelper.GetResource(typeof(InjectionBlockHandler), "BlackErrorTemplate_Injection_DE.htm"); response.Write(html); context.ApplicationInstance.CompleteRequest(); } // End Sub ProcessRequest
} // End Sub CreateExe // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx // This will accumulate each of the files named in the fileList into a zip file, // and stream it to the browser. // This approach writes directly to the Response OutputStream. // The browser starts to receive data immediately which should avoid timeout problems. // This also avoids an intermediate memorystream, saving memory on large files. // public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ClearContent(); Response.ClearHeaders(); Response.Clear(); Response.Buffer = false; Response.ContentType = "application/zip"; // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that // Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); // Response.CacheControl = "Private"; // Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition // http://stackoverflow.com/questions/9303919/pack-empty-directory-with-sharpziplib byte[] buffer = new byte[4096]; using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream)) { zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression // zipOutputStream.Dispose // Empty folder... foreach (string directoryName in zipFileList) { string dname = "myfolder/"; ZipEntry entry = new ZipEntry(dname); // ZipEntry entry = new ZipEntry(ZipEntry.CleanName(dname)); // entry.Size = fs.Length; zipOutputStream.PutNextEntry(entry); } // Next directoryName foreach (string fileName in zipFileList) { // or any suitable inputstream using (System.IO.Stream fs = System.IO.File.OpenRead(fileName)) { ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!Response.IsClientConnected) { break; } Response.Flush(); } // Whend fs.Close(); } // End Using fs } // Next fileName zipOutputStream.Close(); } // End Using zipOutputStream Response.Flush(); Response.End(); } // End Function DownloadZipToBrowser