/// <summary> /// Download the file /// </summary> /// <param name="filePath">The file path</param> public static void DownloadFile(string filePath) { filePath = Utilities.FixRoot(filePath); FileInformation = new FileInfo(filePath); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); if (FileInformation.Name.EndsWith(".txt")) { response.ContentType = "text/plain"; } else if (FileInformation.Name.EndsWith(".jpg")) { response.ContentType = "image/jpg"; } if (FileInformation.Name.Equals("readme.html")) { response.TransmitFile(filePath); response.Flush(); response.End(); return; } response.AppendHeader("Content-Disposition", "attachment; filename=\"" + FileInformation.Name + "\";"); response.TransmitFile(filePath); response.Flush(); response.End(); }
//---------------------------------------------------------------------------------------------------- /// <summary></summary> /// <param name="report"></param> /// <param name="response"></param> public static void ResponsePDF(Report report, System.Web.HttpResponse response, string fileName) { if (report.formatter == null) { report.Init(new PdfFormatter()); } if (report.page_Cur == null) { report.Create(); } response.Clear(); response.Buffer = true; response.ContentType = "application/pdf"; response.Charset = ""; response.ContentEncoding = System.Text.Encoding.Default; response.ClearContent(); response.AddHeader("Content-Disposition", "filename=" + fileName + ".pdf"); MemoryStream ms = new MemoryStream(); report.formatter.Create(report, ms); ms.Close(); response.BinaryWrite(ms.GetBuffer()); response.End(); }
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); }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(Server.MapPath("FileDownload.csv")); response.Flush(); response.End(); }
public void DownloadFile(string fileName, byte[] csvData) { //string fileName = fileNameBuilder(id); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.BinaryWrite(csvData); response.Flush(); response.End(); }
protected void TransmitFile(string filePath, string filename) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ";"); response.TransmitFile(filePath); response.Flush(); response.End(); }
//public void DownloadFile(Guid? id) public void DownloadFile(string fileName) { //string fileName = fileNameBuilder(id); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile("C:\\reports\\" + fileName); response.Flush(); response.End(); }
protected void Button1_Click(object sender, EventArgs e) { CreateBarcodePdf(); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(AppPath + @"Files\Barcode\" + FileName); response.Flush(); //File.Delete(FilePath); //File.Delete(FilePath + ".gif"); response.End(); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AppendHeader("content-length", stream.Length.ToString()); byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); // Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); // Display an error on the webpage. System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page; page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true); return(false); } }
/// <summary> /// Handles a fatal server exception. /// </summary> public static void HandleFatalServerException() { System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response; resp.ClearContent(); resp.StatusCode = 400; resp.AddHeader("Status", "400 Bad Request"); // resp.StatusDescription = "Not Found"; // resp.Write("404 Not Found"); //resp.Flush(); resp.Write("<html><body><strong>The page that you requested caused a server error.</strong><p><em>Please try back later, or try visiting our <a href=\"" + CmsContext.ApplicationPath + "\">home page</a>.</em></p></body></html>"); resp.End(); return; }
protected void btnDownload_Click(object sender, EventArgs e) { //string ten = ViewState["FileName"].ToString().Trim(); string filePath = Format(ViewState["FileName"].ToString().Trim()); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = ContentType; response.AddHeader("Content-Disposition", "attachment; filename=" + filePath + ";"); response.TransmitFile(Server.MapPath("~/Files/" + filePath)); response.Flush(); response.End(); }
public static void ResponseExcel <T>(System.Web.HttpResponse response, List <T> items) { try { string attachment = "attachment; filename=vauExcel.xls"; response.ClearContent(); response.AddHeader("content-disposition", attachment); response.ContentType = "application/vnd.ms-excel"; string tab = string.Empty; // Get all the properties PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { response.Write(tab + prop.Name); tab = "\t"; } response.Write("\n"); foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); if (values[i] != null) { response.Write(values[i].ToString().Trim() + "\t"); } else { response.Write("\t"); } } response.Write("\n"); } response.Flush(); response.Close(); } catch (Exception ex) { throw ex; } }
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(); }
public void ProcessRequest(HttpContext context) { // retrieve your xbook System.IO.MemoryStream ms = new System.IO.MemoryStream(); xbook.Save(ms, C1.C1Excel.FileFormat.Biff8); xbook.Dispose(); ms.Position = 0; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition","attachment;filename=CategoryReport.xls"); Response.BufferOutput = true; Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length); response.Flush(); response.End(); }
/// <summary> /// Handle PageNotFound (404) errors. /// <para>If the useInternal404NotFoundErrorHandler config entry is true, will send the user to the page /// specified by Internal404NotFoundErrorHandlerPageUrl config entry.</para> /// </summary> public static void HandleNotFoundException() { bool useInternal404NotFoundErrorHandler = CmsConfig.getConfigValue("useInternal404NotFoundErrorHandler", false); if (useInternal404NotFoundErrorHandler) { string defaultUrl = ""; if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null) { defaultUrl = System.Web.HttpContext.Current.Request.Url.PathAndQuery; } string fromUrl = PageUtils.getFromForm("aspxerrorpath", defaultUrl); fromUrl = System.Web.HttpUtility.UrlEncode(fromUrl); string Internal404NotFoundErrorHandlerPageUrl = CmsContext.ApplicationPath + "/_internal/error404.aspx?from=" + fromUrl; if (CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", "") != "") { Internal404NotFoundErrorHandlerPageUrl = String.Format(CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", ""), fromUrl); } // use Server.Transfer (And not Response.Redirect) to hide the CMS URL from the user. System.Web.HttpContext.Current.Server.Transfer(Internal404NotFoundErrorHandlerPageUrl); return; } else { // <?php header("HTTP/1.1 404 Not Found"); ?> // <?php header("Status: 404 Not Found"); ?> System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response; resp.ClearContent(); resp.StatusCode = 404; resp.AddHeader("Status", "404 Not Found"); resp.Write("<html><body><strong>The page that you requested does not exist.</strong><p><em>Visit our <a href=\"" + CmsContext.ApplicationPath + "\">home page here</a></em></p></body></html>"); resp.End(); return; // throw new System.Web.HttpException(404, "File Not Found"); //http://forums.asp.net/t/762031.aspx } }
public static void ResponsePDF(Report report, System.Web.HttpResponse response) { if (report.formatter == null) { report.Init(new PdfFormatter()); } if (report.page_Cur == null) { report.Create(); } response.ClearContent(); response.ContentType = "application/pdf"; MemoryStream ms = new MemoryStream(20000); report.formatter.Create(report, ms); ms.Close(); response.BinaryWrite(ms.GetBuffer()); response.End(); }
protected void hlnkDownload_Click(object sender, EventArgs e) { try { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=MasterEmployeeData.xlsx;"); response.TransmitFile(Server.MapPath("~/Data/MasterEmployeeData.xlsx")); response.Flush(); response.End(); } catch (Exception ex) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Something went wrong. Check Log."; ExceptionManager.LogError(ex); } }
} // 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
/// <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 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> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document, filename); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.ms-excel"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { System.IO.File.WriteAllText(@"D:\DSPBlackRock\errormessage.txt", "Failed, exception thrown: " + ex.Message); return(false); } }
public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
//OpenXML kullanarak DataSeti Excel (.xlsx) dosyasına çevirip indirmek // REFERANSLAR // *************************************** // DocumentFormat.OpenXml // WindowsBase //Bu iki referans projeye bir kez eklenir // *************************************** public static bool ExcelOlusturIndir(DataSet ds, string dosyaadi, System.Web.HttpResponse Response) { try { //"HttpCacheability does not exist" hatası alırsanız projeye System.Web referansını ekleyin System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument dosya = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { DataSetExceleYaz(ds, dosya); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + dosyaadi); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { Trace.WriteLine("Hata oluştu: " + ex.Message); return(false); } }
// // GET: /ExportToImage/ public ActionResult Index(string Format = "png") { string baseURL = Request.Url.Authority; if (Request.ServerVariables["HTTPS"] == "on") { baseURL = "https://" + baseURL; } else { baseURL = "http://" + baseURL; } // Check for license and apply if exists string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic"); if (System.IO.File.Exists(licenseFile)) { License license = new License(); license.SetLicense(licenseFile); } //Null value Check if (Request.UrlReferrer != null) { string refUrl = Request.UrlReferrer.AbsoluteUri; string html = new WebClient().DownloadString(refUrl); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(html)); Document doc = new Document(memoryStream); string fileName = ""; if (doc.PageCount > 1) { Directory.CreateDirectory(Server.MapPath("~/Images/" + "Zip")); } ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); if (Format.Contains("png")) { options = new ImageSaveOptions(SaveFormat.Png); options.PageCount = 1; } else if (Format.Contains("JPEG")) { options = new ImageSaveOptions(SaveFormat.Jpeg); options.PageCount = 1; } else if (Format.Contains("TIFF")) { options = new ImageSaveOptions(SaveFormat.Tiff); options.PageCount = 1; } else if (Format.Contains("bmp")) { options = new ImageSaveOptions(SaveFormat.Bmp); options.PageCount = 1; } // Check for Images folder string path = Server.MapPath("~/Images"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Convert the html , get page count and save PNG's in Images folder for (int i = 0; i < doc.PageCount; i++) { if (Format.Contains("TIFF")) { options.PageCount = doc.PageCount; fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); break; } else { options.PageIndex = i; if (doc.PageCount > 1) { fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); } else { // webpage count is 1 fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); } } } /* if webpage count is more then one download images as a Zip but if image type if TIFF * dont download as a zip because Tiff already have all content in one Image */ if (doc.PageCount > 1 && !Format.Contains("TIFF")) { try { string ImagePath = Server.MapPath("~/Images/Zip/"); string downloadDirectory = Server.MapPath("~/Images/"); ZipFile.CreateFromDirectory(ImagePath, downloadDirectory + "OutputImages.zip"); // Prompts user to save file System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/zip"; response.AddHeader("Content-Disposition", "attachment; filename=OutputImages.zip" + ";"); response.TransmitFile(downloadDirectory + "OutputImages.zip"); response.End(); Directory.Delete(ImagePath, true); System.IO.File.Delete(downloadDirectory + "OutputImages.zip"); } catch (Exception Ex) { } } else { string filepath = Server.MapPath("~/Images/Zip/") + fileName; string downloadDirectory = Server.MapPath("~/Images/Zip/"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "image/" + Format; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(filepath); response.End(); Directory.Delete(downloadDirectory, true); } } //set the view to your default View (in my case its home index view) return(RedirectToAction("index", "Home")); }
} // 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
// GET: /ExportToImage/ public ActionResult Index(string Format = "png") { // License this component using an Aspose.Words license file, // if one exists at this location in the local file system. string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic"); if (System.IO.File.Exists(licenseFile)) { License license = new License(); license.SetLicense(licenseFile); } if (Request.UrlReferrer == null) { return(RedirectToAction("index", "Home")); } string refUrl = Request.UrlReferrer.AbsoluteUri; string html = new WebClient().DownloadString(refUrl); Document doc; using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(html))) { doc = new Document(memoryStream); } string imageFileName = ""; if (doc.PageCount > 1) { Directory.CreateDirectory(Server.MapPath("~/Images/" + "Zip")); } ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); if (Format.Contains("png")) { options = new ImageSaveOptions(SaveFormat.Png); options.PageSet = new PageSet(0); } else if (Format.Contains("JPEG")) { options = new ImageSaveOptions(SaveFormat.Jpeg); options.PageSet = new PageSet(0); } else if (Format.Contains("TIFF")) { options = new ImageSaveOptions(SaveFormat.Tiff); options.PageSet = new PageSet(0); } else if (Format.Contains("bmp")) { options = new ImageSaveOptions(SaveFormat.Bmp); options.PageSet = new PageSet(0); } // Create an "Images" folder, and populate it with images that we will render the document into. string imageFolderPath = Server.MapPath("~/Images"); if (!Directory.Exists(imageFolderPath)) { Directory.CreateDirectory(imageFolderPath); } for (int i = 0; i < doc.PageCount; i++) { imageFileName = $"{i}_{Guid.NewGuid()}.{Format}";; if (Format.Contains("TIFF")) { options.PageSet = PageSet.All; doc.Save(Server.MapPath("~/Images/Zip/") + imageFileName, options); } else { options.PageSet = new PageSet(i); if (doc.PageCount > 1) { doc.Save(Server.MapPath("~/Images/Zip/") + imageFileName, options); } else { doc.Save(Server.MapPath("~/Images/Zip/") + imageFileName, options); } } } // If a webpage is large enough for multiple images, and the output image type is not "Tiff", // then download them all in one Zip. A single Tiff file will contain // all the images, so we do not need a Zip archive in this case. if (doc.PageCount > 1 && !Format.Contains("TIFF")) { string ImagePath = Server.MapPath("~/Images/Zip/"); string downloadDirectory = Server.MapPath("~/Images/"); ZipFile.CreateFromDirectory(ImagePath, downloadDirectory + "OutputImages.zip"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/zip"; response.AddHeader("Content-Disposition", "attachment; filename=OutputImages.zip" + ";"); response.TransmitFile(downloadDirectory + "OutputImages.zip"); response.End(); Directory.Delete(ImagePath, true); System.IO.File.Delete(downloadDirectory + "OutputImages.zip"); } else { string filepath = Server.MapPath("~/Images/Zip/") + imageFileName; string downloadDirectory = Server.MapPath("~/Images/Zip/"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "image/" + Format; response.AddHeader("Content-Disposition", "attachment; filename=" + imageFileName + ";"); response.TransmitFile(filepath); response.End(); Directory.Delete(downloadDirectory, true); } return(RedirectToAction("index", "Home")); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStreamList(DataSet dtSet, string filename, System.Web.HttpResponse Response) { try { foreach (DataTable dtSchema in dtSet.Tables) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); int RowInCell = 63000; DataTable ResultsData = new DataTable(); ResultsData = dtSchema.Clone(); int c = 0; int rowNumber = 0; bool firstTime = true; foreach (DataRow rows in dtSchema.Rows) { DataRow row = ResultsData.NewRow(); ResultsData.ImportRow(rows); // ResultsData.Rows.Add(rows); // ResultsData.Rows.Add(rows); if (c == RowInCell) { c = 0; //ExportToOxml(firstTime, ResultsData, filename); ExportToOxml(firstTime, ResultsData, stream); ResultsData.Clear(); firstTime = false; } if (rowNumber == dtSchema.Rows.Count - 1) { c = 0; //ExportToOxml(firstTime, ResultsData, filename); ExportToOxml(firstTime, ResultsData, stream); ResultsData.Clear(); firstTime = false; } c++; rowNumber++; } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } } catch (Exception ex) { Common.WriteLog(ex.Message + "\n" + ex.InnerException + "\n" + ex.StackTrace); return(false); } return(false); }
} // 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