public void Process(System.Web.HttpResponse response) { response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(_filePath)); response.AddHeader("Content-Transfer-Encoding", "binary"); response.ContentType = "application/octet-stream"; response.Cache.SetCacheability(HttpCacheability.NoCache); if (_filePath.StartsWith("http")) { System.Net.WebClient net = new System.Net.WebClient(); var file = net.DownloadData(_filePath); response.BinaryWrite(file); response.End(); } else { response.WriteFile(_filePath); } }
public static void ExportToCsv(System.Web.HttpResponse response, DataTable exportData, string exportName) { response.Clear(); byte[] BOM = { 0xEF, 0xBB, 0xBF }; // UTF-8 BOM karakterleri response.BinaryWrite(BOM); StringBuilder sb = new StringBuilder(); foreach (DataColumn dc in exportData.Columns) { sb.Append((char)(34) + dc.ColumnName + (char)(34)); sb.Append(";"); } sb = sb.Remove(sb.Length - 1, 1); sb.AppendLine(); foreach (DataRow dr in exportData.Rows) { for (int i = 0; i < exportData.Columns.Count; i++) { sb.Append(dr[i].ToString().Replace(';', ',').Replace('\n', ' ').Replace('\t', ' ').Replace('\r', ' ')); sb.Append(";"); } sb = sb.Remove(sb.Length - 1, 1); sb.AppendLine(); } response.ContentType = "text/csv"; response.AppendHeader("Content-Disposition", "attachment; filename=" + exportName + ".csv"); response.Write(sb.ToString()); response.End(); }
public static bool Render(System.Web.HttpResponseBase Response, Excel.IWorkbookBase workbook, string fileName) { // AiLib.Report.Excel.IWorkbookBase workbook // http://dotnetslackers.com/articles/aspnet/Create-Excel-Spreadsheets-Using-NPOI.aspx // Save the Excel spreadsheet to a MemoryStream and return it to the client using (var exportData = new MemoryStream()) { workbook.Write(exportData); string saveAsFileName = fileName; Response.ContentType = ContentExcel; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName)); Response.Clear(); Response.BinaryWrite(exportData.GetBuffer()); Response.End(); } return true; }
private bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath) { try { Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312"); System.IO.FileStream fs = System.IO.File.OpenRead(fullPath); long fLen = fs.Length; int size = 102400;//每100K同时下载数据 byte[] readData = new byte[size];//指定缓冲区的大小 if (size > fLen) size = Convert.ToInt32(fLen); long fPos = 0; bool isEnd = false; while (!isEnd) { if ((fPos + size) > fLen) { size = Convert.ToInt32(fLen - fPos); readData = new byte[size]; isEnd = true; } fs.Read(readData, 0, size);//读入一个压缩块 Response.BinaryWrite(readData); fPos += size; } fs.Close(); System.IO.File.Delete(fullPath); return true; } catch { return false; } }
public override void SendResponse( System.Web.HttpResponse response ) { this.CheckConnector(); try { this.CheckRequest(); } catch ( ConnectorException connectorException ) { response.AddHeader( "X-CKFinder-Error", ( connectorException.Number ).ToString() ); response.StatusCode = 403; response.End(); return; } catch { response.AddHeader( "X-CKFinder-Error", ( (int)Errors.Unknown ).ToString() ); response.StatusCode = 403; response.End(); return; } if ( !Config.Current.Thumbnails.Enabled ) { response.AddHeader( "X-CKFinder-Error", ((int)Errors.ThumbnailsDisabled).ToString() ); response.StatusCode = 403; response.End(); return; } if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileView ) ) { response.AddHeader( "X-CKFinder-Error", ( (int)Errors.Unauthorized ).ToString() ); response.StatusCode = 403; response.End(); return; } bool is304 = false; string fileName = HttpContext.Current.Request[ "FileName" ]; string thumbFilePath = System.IO.Path.Combine( this.CurrentFolder.ThumbsServerPath, fileName ); if ( !Connector.CheckFileName( fileName ) ) { response.AddHeader( "X-CKFinder-Error", ( (int)Errors.InvalidRequest ).ToString() ); response.StatusCode = 403; response.End(); return; } if ( Config.Current.CheckIsHiddenFile( fileName ) ) { response.AddHeader( "X-CKFinder-Error", ( (int)Errors.FileNotFound ).ToString() + " - Hidden folder" ); response.StatusCode = 404; response.End(); return; } // If the thumbnail file doesn't exists, create it now. if ( !Achilles.Acme.Storage.IO.File.Exists( thumbFilePath ) ) { string sourceFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName ); if ( !Achilles.Acme.Storage.IO.File.Exists( sourceFilePath ) ) { response.AddHeader( "X-CKFinder-Error", ( (int)Errors.FileNotFound ).ToString() ); response.StatusCode = 404; response.End(); return; } // TJT: Utilize Stream IO here ImageTools.ResizeImage( sourceFilePath, thumbFilePath, Config.Current.Thumbnails.MaxWidth, Config.Current.Thumbnails.MaxHeight, true, Config.Current.Thumbnails.Quality ); } Achilles.Acme.Storage.IO.FileInfo thumbfile = new Achilles.Acme.Storage.IO.FileInfo( thumbFilePath ) ; string eTag = thumbfile.LastWriteTime.Ticks.ToString( "X" ) + "-" + thumbfile.Length.ToString( "X" ); string chachedETag = Request.ServerVariables[ "HTTP_IF_NONE_MATCH" ]; if ( chachedETag != null && chachedETag.Length > 0 && eTag == chachedETag ) { is304 = true ; } if ( !is304 ) { string cachedTimeStr = Request.ServerVariables[ "HTTP_IF_MODIFIED_SINCE" ]; if ( cachedTimeStr != null && cachedTimeStr.Length > 0 ) { try { DateTime cachedTime = DateTime.Parse( cachedTimeStr ); if ( cachedTime >= thumbfile.LastWriteTime ) is304 = true; } catch { is304 = false; } } } if ( is304 ) { response.StatusCode = 304; response.End(); return; } string thumbFileExt = System.IO.Path.GetExtension( thumbFilePath ).TrimStart( '.' ).ToLower() ; if ( thumbFilePath == ".jpg" ) response.ContentType = "image/jpeg"; else response.ContentType = "image/" + thumbFileExt; response.Cache.SetETag( eTag ); response.Cache.SetLastModified( thumbfile.LastWriteTime ); response.Cache.SetCacheability( HttpCacheability.Private ); // TJT: We need to access the file stream and read the contents into memory System.IO.Stream thumbStream = Achilles.Acme.Storage.IO.File.OpenRead( thumbFilePath ); int bufferSize = (int)thumbStream.Length; if ( bufferSize > 0 ) { byte[] buffer = new byte[bufferSize]; int count = thumbStream.Read( buffer, 0, bufferSize ); response.BinaryWrite( buffer ); } }
public static void DownloadFile(System.Web.HttpResponse objResponse, string strFileName, byte[] FileBytes, string strExtension, bool bPromptForDownload) { string strType = ""; //Set Content Type for Response if (strExtension.LastIndexOf(".") > -1) { strExtension = strExtension.Substring(strExtension.LastIndexOf(".") + 1); } switch (strExtension) { case "Xml": strType = "text/Xml"; break; case "htm": strType = "text/HTML"; break; case "html": strType = "text/HTML"; break; case "txt": strType = "text/plain"; break; case "json": strType = "application/json"; break; case "pdf": strType = "application/pdf"; break; case "xls": strType = "application/vnd.ms-excel"; break; case "rtf": strType = "application/rtf"; break; case "xhtml": strType = "text/xhtml"; break; case "asp": strType = "text/asp"; break; //audio file types case "wav": strType = "audio/x-wav"; break; case "mpg": strType = "audio/mpeg"; break; case "mp3": strType = "audio/mpeg3"; break; case "wmv": strType = "audio/x-ms-wmv"; break; //image file types case "gif": strType = "image/gif"; break; case "jpg": strType = "image/jpeg"; break; case "jpeg": strType = "image/jpeg"; break; case "png": strType = "image/png"; break; //video file types case "avi": strType = "video/avi"; break; case "dat": strType = "video/mpeg"; break; case "mov": strType = "video/quicktime"; break; case "mpeg": strType = "video/mpeg"; break; default: //Handle All Other Files strType = "application/octet-stream"; break; } if ((strExtension != null)) { objResponse.Clear(); objResponse.Buffer = false; objResponse.ContentType = strType; //ensure when building the file name that all forbidden //file name characters are replaced with if (bPromptForDownload) { objResponse.AddHeader("content-disposition", "attachment; filename=" + strFileName + "." + strExtension); } else { objResponse.AddHeader("content-disposition", "filename=" + strFileName + "." + strExtension); } objResponse.AddHeader("Content-Length", Convert.ToString(FileBytes.Length)); objResponse.BinaryWrite(FileBytes); objResponse.Flush(); objResponse.End(); } }
/// <summary> /// 文件下载 /// </summary> /// <param name="_Request"></param> /// <param name="_Response"></param> /// <param name="_fullPath">源文件路径</param> /// <param name="_speed"></param> /// <returns></returns> public static bool DownloadFile(System.Web.HttpRequest _Request, System.Web.HttpResponse _Response, string _fullPath, long _speed) { string _fileName = GetFileName(false, _fullPath); try { FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; double pack = 10240; //10K bytes //int sleep = 200; //每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor(1000 * pack / _speed) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString()))); System.Threading.Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; }
public void ResponseFile(System.Web.HttpResponse response, string fileUId) { Box.CMS.File file = cms.GetFile(fileUId); if (file == null) response.End(); response.ContentType = file.Type; response.BinaryWrite(file.Data.StoredData); response.End(); }
public static void Display(System.Web.HttpResponse response, COMMON.ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, bool isAppendImage) { response.ClearContent(); response.ContentType = "image/Jpeg"; response.BinaryWrite(GetBytes(matrix, format, isAppendImage)); response.End(); }
/// <summary> /// Permite descargar un archivo al PC del cliente /// </summary> /// <param name="objResponse">Objeto response de la pagina desde donde se descarga el archivo</param> /// <param name="path_download">Ruta fisica del archivo</param> /// <param name="nomArchivoDescarga">Nombre con el que se decarga el archivo</param> public static void downloadFile(System.Web.HttpResponse objResponse, string pathDownload) { FileStream stream = null; BinaryReader objBinaryReader = null; Byte[] objByte = { }; if (File.Exists(pathDownload)) { try { stream = new FileStream(pathDownload, FileMode.Open, FileAccess.Read); objBinaryReader = new BinaryReader(stream); objByte = objBinaryReader.ReadBytes((int)stream.Length); objResponse.ClearHeaders(); objResponse.ClearContent(); switch (Path.GetExtension(pathDownload).ToUpper()) { case ".ZIP": objResponse.ContentType = "application/zip"; break; case ".PDF": objResponse.ContentType = "application/pdf"; break; default: objResponse.ContentType = "application/txt"; break; } objResponse.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(pathDownload)); objResponse.BinaryWrite(objByte); //objResponse.WriteFile(pathDownload); objResponse.Flush(); objResponse.Close(); } catch (Exception ex) { throw ex; } } }