/// <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; } } }
public override void SendResponse( System.Web.HttpResponse response ) { int iErrorNumber = 0; string sFileName = ""; string sFilePath = ""; string sUnsafeFileName = ""; try { this.CheckConnector(); this.CheckRequest(); if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileUpload ) ) { ConnectorException.Throw( Errors.Unauthorized ); } HttpPostedFile oFile = null; if ( HttpContext.Current.Request.Files["upload"] != null ) { oFile = HttpContext.Current.Request.Files["upload"]; } else if ( HttpContext.Current.Request.Files["NewFile"] != null ) { oFile = HttpContext.Current.Request.Files["NewFile"]; } else if ( HttpContext.Current.Request.Files.AllKeys.Length > 0 ) { oFile = HttpContext.Current.Request.Files[HttpContext.Current.Request.Files.AllKeys[0]]; } if ( oFile != null ) { int iPathIndex = oFile.FileName.LastIndexOf( "\\" ); sFileName = ( iPathIndex >= 0 && oFile.FileName.Length > 1 ) ? oFile.FileName.Substring( iPathIndex + 1 ) : oFile.FileName; if ( Config.Current.CheckDoubleExtension ) sFileName = this.CurrentFolder.ResourceTypeInfo.ReplaceInvalidDoubleExtensions( sFileName ); sUnsafeFileName = sFileName; if ( Config.Current.DisallowUnsafeCharacters ) sFileName = sFileName.Replace(";","_"); // Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.Current.ForceSingleExtension ) sFileName = Regex.Replace( sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None ); if ( sFileName != sUnsafeFileName ) iErrorNumber = Errors.UploadedInvalidNameRenamed; if ( Connector.CheckFileName( sFileName ) && !Config.Current.CheckIsHiddenFile( sFileName ) ) { if ( !Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize ) ConnectorException.Throw( Errors.UploadedTooBig ); string sExtension = System.IO.Path.GetExtension( sFileName ); sExtension = sExtension.TrimStart( '.' ); if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( sExtension ) ) ConnectorException.Throw( Errors.InvalidExtension ); if ( Config.Current.CheckIsNonHtmlExtension( sExtension ) && !this.CheckNonHtmlFile( oFile ) ) ConnectorException.Throw( Errors.UploadedWrongHtmlFile ); // Map the virtual path to the local server path. string sServerDir = this.CurrentFolder.ServerPath; string sFileNameNoExt = CKFinder.Connector.Util.GetFileNameWithoutExtension( sFileName ); string sFullExtension = CKFinder.Connector.Util.GetExtension( sFileName ); int iCounter = 0; // System.IO.File.Exists in C# does not return true for protcted files if ( Regex.IsMatch( sFileNameNoExt, @"^(AUX|COM\d|CLOCK\$|CON|NUL|PRN|LPT\d)$", RegexOptions.IgnoreCase ) ) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension; iErrorNumber = Errors.UploadedFileRenamed; } while ( true ) { sFilePath = System.IO.Path.Combine( sServerDir, sFileName ); if ( System.IO.File.Exists( sFilePath ) ) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension; iErrorNumber = Errors.UploadedFileRenamed; } else { oFile.SaveAs( sFilePath ); if ( Config.Current.SecureImageUploads && ImageTools.IsImageExtension( sExtension ) && !ImageTools.ValidateImage( sFilePath ) ) { System.IO.File.Delete( sFilePath ); ConnectorException.Throw( Errors.UploadedCorrupt ); } Settings.Images imagesSettings = Config.Current.Images; if ( imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0 ) { ImageTools.ResizeImage( sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality ); if ( Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 ) { long fileSize = new System.IO.FileInfo( sFilePath ).Length; if ( fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize ) { System.IO.File.Delete( sFilePath ); ConnectorException.Throw( Errors.UploadedTooBig ); } } } break; } } } else ConnectorException.Throw( Errors.InvalidName ); } else ConnectorException.Throw( Errors.UploadedCorrupt ); } catch ( ConnectorException connectorException ) { iErrorNumber = connectorException.Number; } catch ( System.Security.SecurityException ) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch ( System.UnauthorizedAccessException ) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch { #if DEBUG throw; #else iErrorNumber = Errors.Unknown; #endif } #if DEBUG if ( iErrorNumber == Errors.None || iErrorNumber == Errors.UploadedFileRenamed || iErrorNumber == Errors.UploadedInvalidNameRenamed ) response.Clear(); #else response.Clear(); #endif System.Web.HttpRequest _Request = System.Web.HttpContext.Current.Request; // CKFinder 2.x flash component if ( _Request.QueryString["response_type"] != null && "txt" == _Request.QueryString["response_type"].ToString() ) { string _errorMsg = ""; if ( iErrorNumber > 0 ) { _errorMsg = Lang.getErrorMessage( iErrorNumber ).Replace( "%1", sFileName ); if ( iErrorNumber != Errors.UploadedFileRenamed && iErrorNumber != Errors.UploadedInvalidNameRenamed ) sFileName = ""; } response.Write( sFileName + "|" + _errorMsg ); } // CKEditor 4.5.0+ else if ( _Request.QueryString["responseType"] != null && "json" == _Request.QueryString["responseType"].ToString() ) { // Cleans the response buffer. response.ClearHeaders(); response.Clear(); // Prevent the browser from caching the result. response.CacheControl = "no-cache"; // Set the response format. response.ContentEncoding = System.Text.UTF8Encoding.UTF8; response.ContentType = "application/json"; string _errorMsg = ""; string fileUrl = this.CurrentFolder.Url + CKFinder.Connector.Util.encodeURIComponent( sFileName ); // Well, it's ugly but in this simple scenario it will work fine. string jsonTemplate = @"""fileName"":""{0}"",""uploaded"":{1}"; string jsonUrlTemplate = @",""url"":""{0}"""; string jsonErrorTemplate = @",""error"":{{""number"":{0},""message"":""{1}""}}"; string jsonResponse; bool uploaded; if ( iErrorNumber > 0 ) { _errorMsg = Lang.getErrorMessage( iErrorNumber ).Replace( "%1", sFileName ); } switch ( iErrorNumber ) { case Errors.None: case Errors.UploadedFileRenamed: case Errors.UploadedInvalidNameRenamed: uploaded = true; break; default: uploaded = false; break; } jsonResponse = "{" + String.Format( jsonTemplate, this.jsonEscape( sFileName ), uploaded ? "1" : "0" ); if ( uploaded ) { jsonResponse += String.Format( jsonUrlTemplate, this.jsonEscape( fileUrl ) ); } if ( iErrorNumber != Errors.None ) { jsonResponse += String.Format( jsonErrorTemplate, iErrorNumber.ToString(), this.jsonEscape( _errorMsg ) ); } jsonResponse += "}"; response.Write( jsonResponse ); } // Other else { response.Write("<script type=\"text/javascript\">"); response.Write( this.GetJavaScriptCode( iErrorNumber, sFileName, this.CurrentFolder.Url ) ); response.Write( "</script>" ); } Connector.CKFinderEvent.ActivateEvent( CKFinderEvent.Hooks.AfterFileUpload, this.CurrentFolder, sFilePath ); 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; string tableName; 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(); Sheet sh = hssfwb.CreateSheet("Sheet1"); int rIndex = 0; Row r = sh.CreateRow(rIndex); int c = 0; foreach (ISDWorksheetCell hCell in row0.Cells) { Cell ce = r.CreateCell(c); ce.SetCellValue(hCell.Text); HSSFCellStyle style = (HSSFCellStyle)hssfwb.CreateCellStyle(); style.WrapText = true; ce.CellStyle = style; c++; } string myValue = ""; for (rIndex = 1; rIndex < rows.Count; rIndex++) { ISDWorksheetRow currentRow = (ISDWorksheetRow)rows[rIndex]; r = sh.CreateRow(rIndex); c = 0; foreach (ISDWorksheetCell dCell in currentRow.Cells) { myValue = dCell.Text.Replace("'", "''"); if (myValue.Length > 255) { myValue = myValue.Substring(0, 255); } Cell ce = r.CreateCell(c); ce.SetCellValue(myValue); HSSFCellStyle style = (HSSFCellStyle)hssfwb.CreateCellStyle(); style.WrapText = true; ce.CellStyle = style; c++; } } 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; }
// 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 + "\""))); }