/// <summary> /// Funcion que permite al usuario descargar un archivo /// </summary> /// <param name="respuesta">Response del sitio web</param> /// <param name="datos">Datos a descargar</param> /// <param name="nombre">Nombre del archivo</param> /// <creador>Jonathan Contreras</creador> /// <fecha_creacion>03-10-2011</fecha_creacion> public void DescargarArchivo(System.Web.HttpResponse respuesta, System.IO.MemoryStream datos, String nombre, String tipo, System.Text.Encoding codificacion) { try { nombre = nombre.Replace(" ", "_"); string[] arrCaracteres = { ",", "?", "¿", "'", "!", "¡", "=", "|", "/", "\\" }; for (int intIndice = 0; intIndice < arrCaracteres.Length; intIndice++) { nombre = nombre.Replace(arrCaracteres[intIndice], string.Empty); } byte[] arrDatos = datos.ToArray(); respuesta.Clear(); respuesta.Buffer = true; respuesta.AddHeader("content-disposition", String.Format("attachment;filename={0}", nombre)); respuesta.AddHeader("Content-Length", arrDatos.Length.ToString()); respuesta.Charset = ""; respuesta.ContentType = tipo; respuesta.ContentEncoding = codificacion; respuesta.BinaryWrite(arrDatos); respuesta.Flush(); respuesta.End(); } catch { } }
private static void GetFile(string person_id, char type, System.Web.HttpResponse Response) { string cmd = ""; switch (type) { case 'P': cmd = "research_dir_user.profile_views.get_profile_picture"; break; case 'C': cmd = "research_dir_user.profile_views.get_profile_cv"; break; default: Response.Write("Error:type not defined"); return; } using (Oracle.DataAccess.Client.OracleConnection orCN = HealthIS.Apps.Util.getDBConnection()) { orCN.Open(); OracleCommand orCmd = new OracleCommand(cmd, orCN); orCmd.CommandType = System.Data.CommandType.StoredProcedure; orCmd.Parameters.Add("p_person_id", OracleDbType.Varchar2).Direction = System.Data.ParameterDirection.Input; orCmd.Parameters["p_person_id"].Value = person_id; orCmd.Parameters.Add("r_cur", OracleDbType.RefCursor).Direction = System.Data.ParameterDirection.Output; OracleDataAdapter adapt = new OracleDataAdapter(orCmd); System.Data.DataSet orDS = new System.Data.DataSet(); orCmd.ExecuteNonQuery(); adapt.Fill(orDS); if (orDS.Tables[0].Rows.Count > 0) { System.Data.DataRow dr = orDS.Tables[0].Rows[0]; byte[] barray = (byte[])dr["file_binary"]; Response.ContentType = (String)dr["file_mimetype"]; Response.AddHeader("Content-Disposition", "attachment; filename=" + person_id + "." + dr["file_ext"].ToString() + ";"); Response.AddHeader("Content-Length", barray.Length.ToString()); Response.OutputStream.Write(barray, 0, barray.Length); } else { Response.Write("Error, no file found for person_id '" + person_id + "'"); } orDS.Dispose(); adapt.Dispose(); orCmd.Dispose(); orCN.Close(); orCN.Dispose(); } }
private void ExportPdfFile(byte[] pdfBytes, string fileName) { pdfConverter.LicenseKey = SF.Framework.SFConfig.EVOPDFKEY; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/pdf"); response.AddHeader("Content-Disposition", String.Format("attachment; filename=" + fileName + ".pdf; size={0}", pdfBytes.Length.ToString())); response.BinaryWrite(pdfBytes); response.End(); }
private void DownloadPDF(byte[] downloadBytes, string downloadName) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + StringHelper.CreateSlug(downloadName) + ".pdf; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); }
public static void RedirectPermanent(this System.Web.HttpResponse response, string uri) { response.StatusCode = 301; response.StatusDescription = "Moved Permanently"; response.AddHeader("Location", uri); 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(); }
public void PrepareResponse(System.Web.HttpResponse httpResponse) { httpResponse.Clear(); httpResponse.ContentType = "text/csv"; httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".csv\""); httpResponse.BufferOutput = false; }
public static void DownloadSimpleZip() { string path = @"D:\Stefan.Steiger\Documents\Visual Studio 2013\Projects\NancyHub\NancyHub\EmbeddedResources"; System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + "Download.zip"); ICSharpCode.SharpZipLib.Zip.FastZip fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip(); fastZip.CreateEmptyDirectories = true; // fastZip.Password = "******"; // Include all files by recursing through the directory structure bool recurse = true; // Dont filter any files at all string filter = null; fastZip.CreateZip(Response.OutputStream, path, true, null, null); // fastZip.CreateZip("fileName.zip", @"C:\SourceDirectory", recurse, filter); } // End Sub DownloadSimpleZip
/// <summary> /// Resposne via OutputStream /// </summary> /// <param name="excel">GlobalClass.Excel instance</param> /// <param name="Response"></param> /// <param name="name"></param> /// <param name="suffix">GlobalClass.Excel.suffix define the type of excel to output</param> /// <param name="cookieKey"></param> /// <param name="cookieValue"></param> /// <example> /// <code language="C#" title="save excel"> /// RF.GlobalClass.Excel excel = new RF.GlobalClass.Excel(); /// excel.createWorksheet(name: "LuckDrawData", headers: new string[] { "NO", "scoreCardCode", "scoreCardOwnerName", "scoreTimes", "Item" }, rowsData: result.data["TableItemList"], suffix:RF.GlobalClass.Excel.suffix.xls); /// RF.GlobalClass.WebForm.Excel.saveAs(excel: excel, Response: Response, name: "LuckDrawData" + RF.GlobalClass.Utils.DateTime.GetDateTimeString(DateTime.Now), suffix: RF.GlobalClass.Excel.suffix.xls); /// </code> /// </example> public static void saveAs(GlobalClass.Excel excel, System.Web.HttpResponse Response, string name = "temp", GlobalClass.Excel.Suffix suffix = GlobalClass.Excel.Suffix.xls, string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; name = name + "." + suffix.ToString(); Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); // Response.Clear(); switch (suffix) { case GlobalClass.Excel.Suffix.xls: System.IO.MemoryStream file = new System.IO.MemoryStream(); excel.hssfworkbook.Write(file); file.WriteTo(Response.OutputStream); break; case GlobalClass.Excel.Suffix.xlsx: excel.package.SaveAs(Response.OutputStream); break; default: break; } } catch (Exception ex) { } }
public void PrepareResponse(System.Web.HttpResponse httpResponse) { httpResponse.Clear(); httpResponse.Charset = System.Text.Encoding.UTF8.ToString(); httpResponse.ContentType = "text/csv;"; httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".csv\""); httpResponse.BufferOutput = false; httpResponse.ContentEncoding = System.Text.Encoding.Default;//.GetEncoding("GB2312"); }
//download file public void saveFile(System.Web.HttpResponse Response, string PathfileName) { string filename = PathfileName; if (filename != "") { string path = filename; System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(file.FullName); 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(); }
/// <summary> /// Response via BinaryWrite /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void binaryWrite(rf.OfficeOpenXml.ExcelPackage package, System.Web.HttpResponse Response, string name = "temp.xlsx", string cookieKey = "Downloaded", string cookieValue = "True") { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + name); Response.Clear(); Response.BinaryWrite(package.GetAsByteArray()); } catch (Exception ex) { } }
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> /// Resposne via OutputStream /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void saveAs(rf.OfficeOpenXml.ExcelPackage package, System.Web.HttpResponse Response, string name = "temp.xlsx", string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); Response.Clear(); package.SaveAs(Response.OutputStream); } catch (Exception ex) { } }
/// <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); } }
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(); }
/// <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; }
/// <summary> /// สำหรับ Zip ไฟล์และ Download /// </summary> /// <param name="httpResponse">Response ของ Page</param> /// <param name="reqDate">วันที่ต้องการ Download</param> /// <param name="tempFolder">Temp Folder</param> public void DownloadLicenseZip(System.Web.HttpResponse httpResponse, DateTime reqDate, string tempFolder) { //เตรียม Directory และ ไฟล์ที่ต้องการ Download string dir = InitRequestLicenseFileToDownload(tempFolder, reqDate); //สำหรับเก็บ Folder ที่ต้อง Zip เพื่อวนหาไฟล์ใน Folder List <string> list = new List <string>(); list.Add(dir); //วนหา Folder ที่ต้อง Zip และ SubFolder ที่อยู่ภายใน GetAllFiles(list, dir); string folderName = string.Empty; //สร้าง Instantce Zip using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { //กำหนด Option Endcode zip.AlternateEncodingUsage = ZipOption.AsNecessary; //วนเ Folder และ SubFolder for (int i = 0; i < list.Count; i++) { //Folder ปัจจุบัน DirectoryInfo dInfo = new DirectoryInfo(list[i]); folderName += (i == 0 ? "" : "\\") + dInfo.Name; //สร้าง Folder ใน Zip zip.AddDirectoryByName(folderName); //วน Add File ใน Folder foreach (string f in Directory.GetFiles(list[i])) { zip.AddFile(f, folderName); } } httpResponse.Clear(); httpResponse.BufferOutput = false; string zipName = String.Format("{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); httpResponse.ContentType = "application/zip"; httpResponse.AddHeader("content-disposition", "attachment; filename=" + zipName); zip.Save(httpResponse.OutputStream); httpResponse.End(); } }
/// <summary> /// Resposne via OutputStream /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void saveAs(rf.NPOI.HSSF.UserModel.HSSFWorkbook hssfworkbook, System.Web.HttpResponse Response, string name = "temp.xls", string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); Response.Clear(); System.IO.MemoryStream file = new System.IO.MemoryStream(); hssfworkbook.Write(file); file.WriteTo(Response.OutputStream); } catch (Exception ex) { } }
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(); }
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; } }
/// <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 } }
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); } }
// zzzzzzz // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx public static void ZipToHttpResponse(string DirectoryToZip) { string ReadmeText = "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G"); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); string fileName = @"Довнлоад.zip"; // @"Довнлоад.зип" fileName = @"Download.zip"; Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + fileName); //using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Response.OutputStream)) using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8)) { // Add to the zip archive, the file selected in the dropdownlist. // zip.AddFile(ListOfFiles.SelectedItem.Text, "files"); // Add a boilerplate copyright file into the zip. // zip.AddFile(@"\static\Copyright.txt", ""); // The string ReadmeText becomes the content for an entry in the zip archive, with the filename "Readme.txt". // zip.AddStringAsFile(ReadmeText, "Readme.txt", ""); zip.Comment = "This will be embedded into a self-extracting exe"; zip.AddEntry("ReadMeZB.txt", ReadmeText); // http://dotnetslackers.com/articles/aspnet/Use-ASP-NET-and-DotNetZip-to-Create-and-Extract-ZIP-Files.aspx // zip.Password = "******"; // zip.Encryption = Ionic.Zip.EncryptionAlgorithm.PkzipWeak; //zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(DirectoryToZip); // recurses subdirectories // zip.Save(); zip.Save(Response.OutputStream); } // End Using zip Response.End(); } // End Sub ZipToHttpResponse
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); }