public static ActionResult GetFile(HttpResponseBase Response, HttpRequestBase Request, HttpServerUtilityBase Server, string filePath, string fileName, string contentType, string userFileName) { byte[] value; using (FileStream stream = System.IO.File.Open(filePath, FileMode.Open)) { value = new byte[stream.Length]; stream.Read(value, 0, (int)stream.Length); } //const string userFileName = "MissionOrder.pdf"; //const string contentType = "application/pdf"; Response.Clear(); if (Request.Browser.Browser == "IE") { string attachment = String.Format("attachment; filename=\"{0}\"", Server.UrlPathEncode(userFileName)); Response.AddHeader("Content-Disposition", attachment); } else Response.AddHeader("Content-Disposition", "attachment; filename=\"" + userFileName + "\""); Response.ContentType = contentType; Response.Charset = "utf-8"; Response.HeaderEncoding = Encoding.UTF8; Response.ContentEncoding = Encoding.UTF8; Response.BinaryWrite(value); Response.End(); return null; }
public static void HandleError(HttpServerUtilityBase server, HttpResponseBase response, CustomErrorsSection customErrorsSection) { CustomError customError = GetCustomError(server.GetLastError(), customErrorsSection); server.ClearError(); response.Clear(); response.WriteFile(customError.Redirect); response.StatusCode = customError.StatusCode; }
/// <summary> /// Exports the specified response. /// </summary> /// <param name="response">The response.</param> /// <param name="myPageName">Name of my page.</param> /// <param name="columns">The columns.</param> /// <param name="ds">The ds.</param> /// <Remarks> /// Created Time: 2008-8-4 10:59 /// Created By: jack_que /// Last Modified Time: /// Last Modified By: /// </Remarks> public static void Export(HttpResponseBase response, string myPageName, List<MESParameterInfo> columns, DataSet ds) { string path = AppDomain.CurrentDomain.BaseDirectory + @"\Excel\" + myPageName + ".xls"; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + myPageName + ".xls"); response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; ExcelWriter excel = new ExcelWriter(path); try { excel.BeginWrite(); short row = 0; for (short k = 0; k < columns.Count; k++) { excel.WriteString(row, k, columns[k].ParamDisplayName); } DataTable dt = ds.Tables[0]; for (short i = 0; i < dt.Rows.Count; i++) { row++; for (short j = 0; j < columns.Count; j++) { MESParameterInfo column = columns[j]; string columnType = column.ParamType; string columnName = column.ParamName; object value = ds.Tables[0].Rows[i][columnName]; if (columnType != null && columnType.Equals("date")) { value = value.ToString().Split(new char[] { ' ' }, StringSplitOptions.None)[0]; } excel.WriteString(row, j, value.ToString()); } } } finally { excel.EndWrite(); } FileInfo file = new FileInfo(path); if (file.Exists) { response.WriteFile(path); response.Flush(); file.Delete(); } }
public static void WriteExcelFile(HttpResponseBase response,string output,string fileName) { response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls"); response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; response.Write(output); }
public void WriteToHttpResponse(HttpResponseBase httpResponse) { httpResponse.Clear(); httpResponse.ContentType = "application/zip"; httpResponse.AddHeader("Content-Disposition", "attachment;filename=remoting-package.zip"); WriteToStream(httpResponse.OutputStream); httpResponse.End(); }
public static void DiplomProjectToWord(string fileName, DiplomProject work, HttpResponseBase response) { response.Clear(); response.Charset = "ru-ru"; response.HeaderEncoding = Encoding.UTF8; response.ContentEncoding = Encoding.UTF8; response.ContentType = "application/vnd.ms-word"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".doc"); CreateDoc(work, response); response.Flush(); response.End(); }
protected override void WriteFile(HttpResponseBase response) { _isRssFeed = _feedType == FeedType.Rss; // Creates Xml file. string xmlFile = HttpContext.Current.Server.MapPath("~/feed.xml"); using (var fileStream = new FileStream(xmlFile, FileMode.Create)) { using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8)) { var xs = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(streamWriter, xs)) { xmlWriter.WriteStartDocument(); if (_isCssStyles) { const string strPi = "type='text/css' href='/Contents/Styles/feedStyle.css'"; // Write processor information xmlWriter.WriteProcessingInstruction("xml-stylesheet", strPi); } if (_isRssFeed) { // RSS 2.0 var rssFormatter = new Rss20FeedFormatter(_feed, true); rssFormatter.WriteTo(xmlWriter); } else { // Atom 1.0 var atomFormatter = new Atom10FeedFormatter(_feed); atomFormatter.WriteTo(xmlWriter); } } } } //Display Xml file in browser. response.Clear(); response.Buffer = true; response.Charset = ""; response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "text/xml"; response.WriteFile(HttpContext.Current.Server.MapPath("~/feed.xml")); response.Flush(); response.End(); }
public void FileDownload(HttpResponseBase response,string filePah) { if(!IsExists(filePah)) { throw new Exception("�ļ�������"); } var fileInfo = new FileInfo(filePah); response.Clear(); response.ClearContent(); response.ClearHeaders(); response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileInfo.Name,System.Text.Encoding.UTF8)); response.AddHeader("Content-Length", fileInfo.Length.ToString()); //response.AddHeader("Content-Transfer-Encoding", "binary"); response.ContentType = "application/vnd.ms-excel;charset=UTF-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.WriteFile(fileInfo.FullName); response.Flush(); response.End(); }
protected override void WriteFile(HttpResponseBase response) { response.Clear(); if(!string.IsNullOrEmpty(Etag)) { response.AppendHeader("ETag", Etag); } response.ContentType = "image/png"; var renderer = new IdenticonRenderer(); using(Bitmap b = renderer.Render(Code, Size)) { using(var stream = new MemoryStream()) { b.Save(stream, ImageFormat.Png); stream.WriteTo(response.OutputStream); } } }
protected override void WriteFile(HttpResponseBase response) { _isRssFeed = _feedType == FeedType.Rss; // Creates Xml file. string xmlFile = HttpContext.Current.Server.MapPath("~/feed.xml"); using (var fileStream = new FileStream(xmlFile, FileMode.Create)) { using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8)) { var xs = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(streamWriter, xs)) { xmlWriter.WriteStartDocument(); if (_isRssFeed) { // RSS 2.0 var rssFormatter = new Rss20FeedFormatter(_feed); rssFormatter.WriteTo(xmlWriter); } else { // Atom 1.0 var atomFormatter = new Atom10FeedFormatter(_feed); atomFormatter.WriteTo(xmlWriter); } } } } XslTransform myXslTransform = new XslTransform(); myXslTransform.Load(HttpContext.Current.Server.MapPath("~/feed.xslt")); myXslTransform.Transform(HttpContext.Current.Server.MapPath("~/feed.xml"), HttpContext.Current.Server.MapPath("~/newFeed.xml")); //Display Xml file in browser. response.Clear(); response.Buffer = true; response.Charset = ""; response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "application/xml"; response.WriteFile(HttpContext.Current.Server.MapPath("~/newFeed.xml")); response.Flush(); response.End(); }
public void ExportToXls(HttpResponseBase Response, List<string> fieldsName, DataTable exportDs, string filename) { Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8))); Response.Clear(); InitializeWorkbook(); GenerateData(fieldsName, exportDs, filename); GetExcelStream().WriteTo(Response.OutputStream); Response.End(); }
/// <summary> /// 创建Excel /// </summary> public static void CreateExcel(HttpResponseBase response, HttpRequestBase request, int[] idArr) { // 文件名 //string fileName = DateTime.Now.ToString("yyyyMMdd") + "测试.xls";、 string fileName = "面试者信息表.xls"; string UserAgent = request.ServerVariables["http_user_agent"].ToLower(); // Firfox和IE下输出中文名显示正常 if (UserAgent.IndexOf("firefox") == -1) { fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); } response.ContentType = "application/vnd.ms-excel;charset=UTF-8"; response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); response.Clear(); // 新建Excel文档 HSSFWorkbook excel = new HSSFWorkbook(); // 新建一个Excel页签 ISheet sheet = excel.CreateSheet("面试者信息表"); //设置居中 ICellStyle cellStyle = excel.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; // 创建新增行 IRow row = sheet.CreateRow(0); // 设计表头 ICell cell = row.CreateCell(0); cell.CellStyle = cellStyle; cell.SetCellValue("ID"); cell = row.CreateCell(1); cell.CellStyle = cellStyle; cell.SetCellValue("学号"); cell = row.CreateCell(2); cell.CellStyle = cellStyle; cell.SetCellValue("姓名"); cell = row.CreateCell(3); cell.CellStyle = cellStyle; cell.SetCellValue("性别"); cell = row.CreateCell(4); cell.CellStyle = cellStyle; cell.SetCellValue("学院"); cell = row.CreateCell(5); cell.CellStyle = cellStyle; cell.SetCellValue("专业"); cell = row.CreateCell(6); cell.CellStyle = cellStyle; cell.SetCellValue("班级"); cell = row.CreateCell(7); cell.CellStyle = cellStyle; cell.SetCellValue("QQ"); cell = row.CreateCell(8); cell.CellStyle = cellStyle; cell.SetCellValue("E-mail"); cell = row.CreateCell(9); cell.CellStyle = cellStyle; cell.SetCellValue("联系方式"); cell = row.CreateCell(10); cell.CellStyle = cellStyle; cell.SetCellValue("学习经验"); cell = row.CreateCell(11); cell.CellStyle = cellStyle; cell.SetCellValue("自我介绍"); cell = row.CreateCell(12); cell.CellStyle = cellStyle; cell.SetCellValue("是否应聘技术方向"); cell = row.CreateCell(13); cell.CellStyle = cellStyle; cell.SetCellValue("选择题得分"); cell = row.CreateCell(14); cell.CellStyle = cellStyle; cell.SetCellValue("简答题得分"); cell = row.CreateCell(15); cell.CellStyle = cellStyle; cell.SetCellValue("总分"); cell = row.CreateCell(16); cell.CellStyle = cellStyle; cell.SetCellValue("评语"); //根据答卷 //表格添加内容 List<MODEL.T_InterviewerInfo> list = OperateContext.Current.BLLSession .IInterviewerInfoBLL.GetListBy(i => idArr.Contains(i.ID)).ToList(); for (int i = 0; i < list.Count; i++) { row = sheet.CreateRow(i + 1); cell = row.CreateCell(0); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].ID); cell = row.CreateCell(1); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Num); cell = row.CreateCell(2); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Name); cell = row.CreateCell(3); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Gender); cell = row.CreateCell(4); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Academy); cell = row.CreateCell(5); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Major); cell = row.CreateCell(6); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Class); cell = row.CreateCell(7); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].QQ); cell = row.CreateCell(8); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].Email); cell = row.CreateCell(9); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].TelNum); cell = row.CreateCell(10); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].LearningExperience); cell = row.CreateCell(11); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].SelfEvaluation); cell = row.CreateCell(12); cell.CellStyle = cellStyle; cell.SetCellValue(list[i].IsRequestTech == true ? "是" : "否"); cell = row.CreateCell(13); cell.CellStyle = cellStyle; cell.SetCellValue(GetChoiceScore(list[i].ID)); cell = row.CreateCell(14); cell.CellStyle = cellStyle; cell.SetCellValue(GetBriefScore(list[i].ID)); cell = row.CreateCell(15); cell.CellStyle = cellStyle; cell.SetCellValue(GetTotalScore(list[i].ID)); cell = row.CreateCell(16); cell.CellStyle = cellStyle; cell.SetCellValue(GetComment(list[i].ID)); } // 设置行宽度 sheet.SetColumnWidth(1, 18 * 256); sheet.SetColumnWidth(4, 22 * 256); sheet.SetColumnWidth(5, 22 * 256); sheet.SetColumnWidth(7, 15 * 256); sheet.SetColumnWidth(8, 21 * 256); sheet.SetColumnWidth(9, 16 * 256); sheet.SetColumnWidth(12, 18 * 256); sheet.SetColumnWidth(16, 30 * 256); //将Excel内容写入到流中 MemoryStream file = new MemoryStream(); excel.Write(file); //输出 response.BinaryWrite(file.GetBuffer()); response.End(); }
/// <summary> /// 创建验证码的图片 /// </summary> /// <param name="containsPage">要输出到的page对象</param> /// <param name="validateNum">验证码</param> public void CreateValidateGraphic(string validateCode,HttpResponseBase Response) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的干扰线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2); //画图片的前景干扰点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存图片数据 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 Response.Clear(); Response.ContentType = "image/jpeg"; Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); image.Dispose(); } }
private static void SetStatusCode(HttpResponseBase response, int code) { response.Clear(); response.TrySkipIisCustomErrors = true; response.StatusCode = code; }
public static void SetResponseAsExcelFile(HttpResponseBase response, string filename) { response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=" + filename); }
/// <summary> /// Exports to excel with out header. /// </summary> /// <param name="response">The response.</param> /// <param name="myPageName">Name of my page.</param> /// <param name="ds">The ds.</param> /// <Remarks> /// Created Time: 08-12-24 14:20 /// Created By: jack_que /// Last Modified Time: /// Last Modified By: /// </Remarks> public static void ExportToExcelWithOutHeader(HttpResponseBase response, string myPageName, DataSet ds) { response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=Sheet1.xls" ); response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; //response.ContentType = "text/csv"; StringBuilder builder = new StringBuilder(); builder.Append("<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>") .Append("<body><table width='100%' border='1'><tr bgcolor='gray' style='COLOR: white'>"); foreach (DataColumn column in ds.Tables[0].Columns) { builder.Append("<td align='center'>").Append(column.ColumnName.ToLower()).Append("</td>"); } builder.Append("</tr>"); foreach (DataRow row in ds.Tables[0].Rows) { builder.Append("<tr>"); foreach (DataColumn column in ds.Tables[0].Columns) { builder.Append("<td>").Append(row[column].ToString()).Append("</td>"); } builder.Append("</tr>"); } builder.Append("</table></body></html>"); response.Output.Write(builder.ToString()); }
/// <summary> /// Exports to excel. /// </summary> /// <param name="response">The response.</param> /// <param name="myPageName">Name of my page.</param> /// <param name="columns">The columns.</param> /// <param name="list">The list.</param> /// <Remarks> /// Created Time: 2008-7-8 15:40 /// Created By: jack_que /// Last Modified Time: /// Last Modified By: /// </Remarks> public static void ExportToExcel(HttpResponseBase response, string myPageName, List<MESParameterInfo> columns,List<Dictionary<string,string>> list) { string FileName = myPageName + ".xls"; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); string ss = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; StringBuilder builder = new StringBuilder(); builder.Append("<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>") .Append("<body><table width='100%' border='1'><tr bgcolor='gray' style='COLOR: white'>"); for (int k = 0; k < columns.Count; k++) { builder.Append("<td align='center'>").Append(columns[k].ParamDisplayName).Append("</td>"); } builder.Append("</tr>"); for (int i = 0; i < list.Count; i++) { Dictionary<string, string> dic = list[i]; builder.Append("<tr>"); for (int j = 0; j < columns.Count; j++) { MESParameterInfo column = columns[j]; string columnType = column.ParamType; string columnName = column.ParamName; string value = dic[columnName]; if (columnType != null && columnType.Equals("date")) { value = value.Split(new char[] { ' ' }, StringSplitOptions.None)[0]; } builder.Append("<td>").Append(value.ToString()).Append("</td>"); } builder.Append("</tr>"); } builder.Append("</table></body></html>"); response.Output.Write(builder.ToString()); }
/// <summary> /// 将响应直接输出 /// </summary> /// <param name="response">HttpResponse 对象,用于输出响应</param> public virtual void Apply( HttpResponseBase response ) { response.Clear(); response.HeaderEncoding = HeaderEncoding; foreach ( var key in Headers.AllKeys ) { foreach ( var value in Headers.GetValues( key ) ) { response.AppendHeader( key, value ); } } response.ContentEncoding = ContentEncoding; response.Write( Content ); }
protected override void WriteFile(HttpResponseBase response) { response.BufferOutput = false; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.Cookies.Clear(); response.ContentType = ContentType; response.ContentEncoding = Encoding.Default; response.AddHeader("Content-Type", ContentType); response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", this.FileDownloadName)); byte[] buffer = new byte[4096]; using (ZipOutputStream zipOutputStream = new ZipOutputStream(response.OutputStream)) { foreach (string fileName in FilesToZip) { int folderOffset = fileName.LastIndexOf('\\'); Stream fs = System.IO.File.OpenRead(fileName); // or any suitable inputstream string entryName = fileName.Substring(folderOffset); ZipEntry entry = new ZipEntry(ZipEntry.CleanName(entryName)); 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); //zipOutputStream.SetLevel(3); // 0-9 for compression level //zipOutputStream.Password(); // security 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(); } fs.Close(); } zipOutputStream.Finish(); } //response.OutputStream.Flush(); response.End(); }
private void WritePlainTextResponse(HttpResponseBase response, Exception exceptionWritingHtml) { log.Fatal(Error.FatalException, exceptionWritingHtml); response.Clear(); response.ContentType = Constants.PlainTextContentType; response.Write(User.FatalException); }
private void ExportToExcel(string exportContent, HttpResponseBase response) { response.Clear(); response.ClearContent(); response.AddHeader("content-disposition", "attachment;filename=" + fileName); response.Charset = ""; response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); response.Write(exportContent); response.End(); }