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 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 );
     response.WriteFile( _filePath );
 }
Exemplo n.º 3
0
 public static void Convert(System.Data.DataSet ds, int TableIndex, System.Web.HttpResponse response, string ExcelName)
 {
     //lets make sure a table actually exists at the passed in value
     //if it is not call the base method
     if (TableIndex > ds.Tables.Count - 1)
     {
         Convert(ds, response, ExcelName);
     }
     //we've got a good table so
     //let's clean up the response.object
     response.Clear();
     response.Charset = "";
     response.AddHeader("Content-Disposition", "attachment;filename=Shilpa.xls");
     //set the response mime type for excel
     response.ContentType = "application/vnd.ms-excel";
     //create a string writer
     System.IO.StringWriter stringWrite = new System.IO.StringWriter();
     //create an htmltextwriter which uses the stringwriter
     System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
     //instantiate a datagrid
     System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
     //set the datagrid datasource to the dataset passed in
     dg.DataSource = ds.Tables[TableIndex];
     //bind the datagrid
     dg.DataBind();
     //tell the datagrid to render itself to our htmltextwriter
     dg.RenderControl(htmlWrite);
     //all that's left is to output the html
     response.Write(stringWrite.ToString());
     response.End();
 }
Exemplo n.º 4
0
    public static void Convert(System.Data.DataSet ds, System.Web.HttpResponse response, string ExcelName)
    {
        try
        {
            //first let's clean up the response.object
            response.Clear();
            response.Charset = "";
            //set the response mime type for excel

            response.ContentType = "application/vnd.ms-excel";
            //create a string writer
            //response.AddHeader("Content-Disposition", "attachment;filename=Shilpa.xls");

            response.AddHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".xls");

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            //create an htmltextwriter which uses the stringwriter
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            //instantiate a datagrid
            System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
            //set the datagrid datasource to the dataset passed in
            dg.DataSource = ds.Tables[0];
            //bind the datagrid
            dg.DataBind();
            //tell the datagrid to render itself to our htmltextwriter
            dg.RenderControl(htmlWrite);
            //all that's left is to output the html
            response.Write(stringWrite.ToString());
            response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 public void PrepareResponse(System.Web.HttpResponse httpResponse)
 {
     httpResponse.Clear();
     httpResponse.ContentType = "text/csv";
     httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".csv\"");
     httpResponse.BufferOutput = false;
 }
Exemplo n.º 6
0
 protected override void WriteFile(System.Web.HttpResponseBase response)
 {
     response.Clear();
     response.AddHeader("content-disposition", "attachment; filename=" + DownloadedFilename);
     response.ContentType = this.ContentType;
     response.WriteFile(Path);
     response.Flush();
     System.IO.File.Delete(Path);
     response.End();
 }
Exemplo n.º 7
0
        public static bool SaveAs(System.Web.HttpResponse Response, string FullFilePath)
        {
            try
            {
                FileInfo myfile = new FileInfo(FullFilePath);

                if (myfile.Exists)
                {
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
                    Response.AddHeader("Content-Length", myfile.Length.ToString());
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.WriteFile(myfile.FullName);
                    Response.End();

                }
                return true;
            }
            catch (ThreadAbortException) { return false; }

        }
Exemplo n.º 8
0
        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;
        }
Exemplo n.º 9
0
        public static void ToExcel(DataTable dataTable, System.Web.HttpResponseBase response)
        {
            using (StringWriter sw = new StringWriter())
            {
                List<string> headers = getTableHeaders(dataTable);
                string sHeaders = getHeadersString(headers);

                sw.WriteLine(sHeaders);

                foreach (DataRow dr in dataTable.Rows)
                {
                    string sRow = getRowString(dr, headers);
                    sw.WriteLine(sRow);
                }

                response.Clear();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=Teest.xls");
                response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                response.ContentType = "application/vnd.ms-excel";
                response.Write(sw);
                response.End();
            }
        }
Exemplo n.º 10
0
        public void ExportToXls(System.Web.HttpResponse 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();
        }
Exemplo n.º 11
0
 protected override void WriteFile(System.Web.HttpResponseBase response)
 {
     // Add the filename to the Content-Disposition
     response.AddHeader("Content-Disposition", ContentDisposition.ToString());
     base.WriteFile(response);
 }
		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 ( !System.IO.File.Exists( thumbFilePath ) )
			{
				string sourceFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName );

				if ( !System.IO.File.Exists( sourceFilePath ) )
				{
					response.AddHeader( "X-CKFinder-Error", ( (int)Errors.FileNotFound ).ToString() );
					response.StatusCode = 404;
					response.End();
					return;
				}

				ImageTools.ResizeImage( sourceFilePath, thumbFilePath, Config.Current.Thumbnails.MaxWidth, Config.Current.Thumbnails.MaxHeight, true, Config.Current.Thumbnails.Quality );
			}

			System.IO.FileInfo thumbfile = new System.IO.FileInfo( thumbFilePath ) ;

			if ( !thumbfile.Exists )
			{
				response.AddHeader("X-CKFinder-Error", ((int)Errors.Unknown).ToString());
				response.StatusCode = 404;
				response.End();
				return;
			}
			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 );

			response.WriteFile( thumbFilePath );
		}
Exemplo n.º 13
0
        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();
            }
        }
Exemplo n.º 14
0
 /// <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;
         }
     }
 }
        /// <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;
        }
Exemplo n.º 16
0
 public static void AddGlobalResponseHeaders(System.Web.HttpResponse httpRes)
 {
     foreach (var globalResponseHeader in Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
Exemplo n.º 17
0
 public static void ExportToExcel(System.Web.HttpResponse response, DataTable exportData, string exportName)
 {
     string attachment = "attachment; filename=" + exportName + ".xls";
     response.ClearContent();
     response.AddHeader("content-disposition", attachment);
     response.ContentType = "application/vnd.ms-excel";
     response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
     response.Charset = "windows-1254";
     string tab = "";
     foreach (DataColumn dc in exportData.Columns)
     {
         response.Write(tab + dc.ColumnName);
         tab = "\t";
     }
     response.Write("\n");
     foreach (DataRow dr in exportData.Rows)
     {
         tab = "";
         for (int i = 0; i < exportData.Columns.Count; i++)
         {
             response.Write(tab + (string.IsNullOrEmpty(dr[i].ToString()) ? "-" : dr[i].ToString().Replace("\t", "").Replace("\r", "").Replace("\n", "")));
             tab = "\t";
         }
         response.Write("\n");
     }
     response.End();
 }
Exemplo n.º 18
0
 public override void HandleFailure(System.Web.HttpResponse response, AuthException ae)
 {
     response.AddHeader("WWW-Authenticate", "Basic realm=\""+Environment.MachineName+"\"");
     response.StatusCode = 401;
 }
Exemplo n.º 19
0
        public void ExportImg2Xls(System.Web.HttpResponse Response, byte[] imgBytes, string filename,int imgHeight,int imgWidth)
        {
            //byte[] bytes = System.IO.File.ReadAllBytes(@"E:\mineown\mine\TrainerEvaluate20140929\untitled.png");
            hssfworkbook=new HSSFWorkbook();
              //  File.WriteAllBytes(@"d:\11.png",imgBytes);
            int pictureIdx = hssfworkbook.AddPicture(imgBytes, PictureType.PNG);
            //create sheet
            var sheet = hssfworkbook.CreateSheet("课程满意度分布");
            // Create the drawing patriarch.  This is the top level container for all shapes.
            var patriarch = sheet.CreateDrawingPatriarch();
            //add a picture
            var anchor = new HSSFClientAnchor(0, 0,1023, 255, 0, 0,10, 18);
            var pict = patriarch.CreatePicture(anchor, pictureIdx);
            pict.Resize(1);

            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls",  HttpUtility.UrlPathEncode(filename)));
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            file.WriteTo(Response.OutputStream);
            Response.End();
        }
Exemplo n.º 20
0
        public void ExportEvReportToxls(System.Web.HttpResponse Response, string filename, Guid courseId)
        {
            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();
            GenerateEvReportData(courseId);
            GetExcelStream().WriteTo(Response.OutputStream);
            Response.End();
        }
Exemplo n.º 21
0
        public string Generate(System.Web.HttpResponse response, string FileName, bool OpenInBrowser)
        {
            StringBuilder sb = new StringBuilder();

            sb = GetHeader(sb);
            sb = GetDocumentProperties(sb);
            sb = GetExcelWorkbook(sb);
            sb = GetStyles(sb);
            sb = GetNames(sb);
            sb = GetWorksheets(sb);
            sb.Append("</Workbook>");

            response.Buffer = false;
            response.Clear();
            response.ContentType = "application/vnd.ms-excel";
            if (!OpenInBrowser)
                response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            response.OutputStream.Write(encoding.GetBytes(sb.ToString()), 0, encoding.GetBytes(sb.ToString()).Length);
            response.Flush();
            response.End();

            return sb.ToString();
        }