예제 #1
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="filePath">要下载的文件的完整路径</param>
        /// <param name="downloadName">下载时要显示的文件名</param>
        /// <param name="isDelete">下载后是否删除文件</param>
        /// <param name="bts">文件的byte</param>
        public void FileDonwLoad(HttpRequestBase Request, HttpResponseBase Response, string downloadName, bool isDelete = false, byte[] bts = null, string filePath = null)
        {
            //以字符流的形式下载文件
            byte[] bytes;
            if (bts == null)
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                //读取完成后删除
                if (isDelete)
                {
                    File.Delete(filePath);
                }
            }
            else
            {
                bytes = bts;
            }
            //下载文件
            Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8");
            if (!string.IsNullOrEmpty(filePath) && filePath.Contains(".xls"))
            {
                Response.ContentType = "application/ms-excel";
            }
            else
            {
                Response.ContentType = "application/octet-stream";
            }

            if (Request.UserAgent.ToLower().IndexOf("msie") > -1)
            {
                downloadName = HttpUtility.UrlPathEncode(downloadName);
            }
            if (Request.UserAgent.ToLower().IndexOf("firefox") > -1)
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + downloadName + "\"");
            }
            else
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName);
            }
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            Response.BinaryWrite(bytes);
            Response.Flush();
            //context.Response.End();
            //清空以免缓存影响下次下载
            Response.Clear();
        }
예제 #2
0
        public void DownloadDir(string path)
        {
            path = FixPath(path);
            if (!Directory.Exists(path))
            {
                throw new Exception(LangRes("E_CreateArchive"));
            }
            string dirName = new FileInfo(path).Name;
            string tmpZip  = _context.Server.MapPath("../tmp/" + dirName + ".zip");

            if (System.IO.File.Exists(tmpZip))
            {
                System.IO.File.Delete(tmpZip);
            }
            ZipFile.CreateFromDirectory(path, tmpZip, CompressionLevel.Fastest, true);
            _r.Clear();
            _r.Headers.Add("Content-Disposition", "attachment; filename=\"" + dirName + ".zip\"");
            _r.ContentType = "application/force-download";
            _r.TransmitFile(tmpZip);
            _r.Flush();
            System.IO.File.Delete(tmpZip);
            _r.End();
        }
예제 #3
0
        private void Export(PageFreshnessReportViewModel model, HttpResponseBase response)
        {
            using (var package = new ExcelPackage())
            {
                AddWorksheet(package, "Top10FreshestPages", model.Top10FreshestPages);
                AddWorksheet(package, "Top10LeastFreshPages", model.Top10LeastFreshPages);

                response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                response.AddHeader("content-disposition", string.Format("attachment; filename=pages{0}.xlsx", DateTime.Now.ToString("yyyyMMdd")));
                response.BinaryWrite(package.GetAsByteArray());
                response.Flush();
                response.End();
            }
        }
예제 #4
0
 private static void WriteCsvFile(HttpResponseBase Response, StringBuilder sb, string sExportedFileName)
 {
     Response.Clear();
     Response.ClearContent();
     Response.ClearHeaders();
     Response.Buffer      = true;
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition",
                        "attachment;filename=" + sExportedFileName + ".csv");
     // Response.ContentType = "application/text";
     Response.ContentEncoding = Encoding.GetEncoding("windows-1256");
     Response.Output.Write(sb.ToString());
     Response.Flush();
     Response.End();
 }
예제 #5
0
        public void ToExcel_XLSX <T>(HttpResponseBase Response, List <T> clientsList)
        {
            ExcelPackage excel     = new ExcelPackage();
            var          workSheet = excel.Workbook.Worksheets.Add("Lotes");

            workSheet.Cells[1, 1].LoadFromCollection(clientsList, true);
            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ListagemLotes.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
        }
예제 #6
0
        public override void OnResultExecuting(ResultExecutionContext context)
        {
            if (_suppressResultFiltering)
            {
                return;
            }

            HttpResponseBase response = context.HttpContext.Response;

            context.HttpContext.Session.UpdateSessionId();

            _filter = response.Filter;
            response.Flush();

            response.Filter = new CaptureFilter(response.Filter);
        }
예제 #7
0
 public void SendFileToWeb(HttpResponseBase Response, PdfDocument document, string FileName)
 {
     if (document.PageCount > 0)
     {
         MemoryStream stream = new MemoryStream();
         document.Save(stream, false);
         Response.Clear();
         Response.ContentType = "application/pdf";
         Response.AddHeader("Content-Length", stream.Length.ToString());
         Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".pdf");
         Response.BinaryWrite(stream.ToArray());
         Response.Flush();
         stream.Close();
         Response.End();
     }
 }
예제 #8
0
        /// <summary>
        /// Downloads the exported report
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult DownloadExportedReport(string fileName)
        {
            HttpResponseBase response = HttpContext.Response;

            response.Clear();
            response.ContentType = PdfMimeType;
            response.AppendHeader(ContentDispositionHeader, ContentDispositionValue + fileName + PdfExtension);

            byte[] pdfBytes = System.IO.File.ReadAllBytes(Path.Combine(AppConstants.ConfigurationKeys.ExportedReportsPath, fileName + PdfExtension));
            response.AddHeader(ContentLengthHeader, pdfBytes.Length.ToString());
            response.BinaryWrite(pdfBytes);

            response.Flush();
            response.End();

            return(new EmptyResult());
        }
예제 #9
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;
            HttpRequestBase  request  = context.HttpContext.Request;

            if (!HttpCacheHelper.IsFileFromCache(File, request, response))
            {
                string fileName;
                string fileNameEncoded = HttpUtility.UrlEncode(File.Name);

                if (context.HttpContext.Request.UserAgent.Contains("MSIE")) // IE < 9 do not support RFC 6266 (RFC 2231/RFC 5987)
                {
                    fileName = "filename=\"" + fileNameEncoded + "\"";
                }
                else
                {
                    fileName = "filename*=UTF-8\'\'" + fileNameEncoded; // RFC 6266 (RFC 2231/RFC 5987)
                }
                string mime;
                string disposition;
                if (IsDownload)
                {
                    mime        = "application/octet-stream";
                    disposition = "attachment; " + fileName;
                }
                else
                {
                    mime        = Helper.GetMimeType(File);
                    disposition = (mime.Contains("image") || mime.Contains("text") || mime == "application/x-shockwave-flash" ? "inline; " : "attachment; ") + fileName;
                }

                response.ContentType = mime;
                response.AppendHeader("Content-Disposition", disposition);
                response.AppendHeader("Content-Location", File.Name);
                response.AppendHeader("Content-Transfer-Encoding", "binary");
                response.AppendHeader("Content-Length", File.Length.ToString());
                response.WriteFile(File.FullName);
                response.End();
                response.Flush();
            }
            else
            {
                response.ContentType = IsDownload ? "application/octet-stream" : Helper.GetMimeType(File);
                response.End();
            }
        }
        public async Task ExportAll(HttpResponseBase Response)
        {
            var complaints = await this.GetAllAsync();

            ExcelPackage   pck = new ExcelPackage();
            ExcelWorksheet ws  = pck.Workbook.Worksheets.Add("Tickets");

            ws.Cells["A1"].Value = "Cliente";
            ws.Cells["B1"].Value = "Tipo";
            ws.Cells["C1"].Value = "Producto";
            ws.Cells["D1"].Value = "Departamento";
            ws.Cells["E1"].Value = "Fecha de Creacion";
            ws.Cells["F1"].Value = "Fecha de Cierre";
            ws.Cells["G1"].Value = "Estado";
            ws.Cells["H1"].Value = "Razon";
            ws.Cells["I1"].Value = "Comentario";


            int rowStart = 2;

            foreach (var item in complaints.Data)
            {
                ws.Cells[$"A{rowStart}"].Value = $"{item.Customer.Name} {item.Customer.LastName}";
                ws.Cells[$"B{rowStart}"].Value = item.TicketType.Description;
                ws.Cells[$"C{rowStart}"].Value = item.Product.Name;
                ws.Cells[$"D{rowStart}"].Value = item.Deparment.Name;
                ws.Cells[$"E{rowStart}"].Value = item.CreatedAt.ToString("MM/dd/yyyy hh:mm tt");
                ws.Cells[$"F{rowStart}"].Value = item.CompletedAt?.ToString("MM/dd/yyyy hh:mm tt");
                ws.Cells[$"G{rowStart}"].Value = item.Status.Name;
                ws.Cells[$"H{rowStart}"].Value = item.ComplaintsOption.Name;
                ws.Cells[$"I{rowStart}"].Value = item.Comment;
                rowStart++;
            }

            ws.Cells["A:AZ"].AutoFitColumns();
            Response.Clear();
            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment; filename=" + $"Tickets-{DateTime.Now:MM-dd-yyyy-hh:mm-ss}" + ".xlsx");
                pck.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
        }
예제 #11
0
 public static void BaixarArquivo(string nomeArquivo, byte[] arquivo, HttpResponseBase response, HttpServerUtilityBase server)
 {
     try
     {
         response.ClearContent();
         response.ContentType = DefinirContextDownloadArquivo(nomeArquivo);
         String Header = "attachment; filename=" + nomeArquivo;
         response.AppendHeader("Content-Disposition", Header);
         response.BinaryWrite(arquivo);
         response.Flush();
         response.End();
     }
     catch
     {
         throw new Exception("ERRO: 2200. </br>" + " NÃO FOI POSSÍVEL FAZER O DOWNLOAD DO ARQUIVO, TENTE NOVAMENTE MAIS TARDE.");
     }
 }
예제 #12
0
        /// <summary>
        /// Stuffs current response from a HttpWebResponse object.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="response"></param>
        public static void StuffFromHttpWebResponse(this HttpResponseBase web, HttpWebResponse response)
        {
            foreach (string name in response.Headers)
            {
                web.AppendHeader(name, response.Headers[name]);
            }

            web.ContentType = response.ContentType;
            web.Charset     = response.CharacterSet;
            if (!string.IsNullOrWhiteSpace(response.CharacterSet))
            {
                Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
                web.ContentEncoding = encoding;
                web.HeaderEncoding  = encoding;
            }
            web.StatusCode        = (int)response.StatusCode;
            web.StatusDescription = response.StatusDescription;

            web.ClearContent();
            if (!string.IsNullOrWhiteSpace(response.Headers["Transfer-Encoding"]) || response.ContentLength < 0)
            {
                int    count  = 0;
                byte[] buffer = new byte[1024 * 1024];
                using (Stream reader = response.GetResponseStream()) {
                    using (Stream writer = web.OutputStream) {
                        while ((count = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            writer.Write(buffer, 0, count);
                        }
                    }
                }
            }
            else
            {
                byte[] data = new byte[response.ContentLength];
                using (Stream reader = response.GetResponseStream()) {
                    reader.Read(data, 0, data.Length);
                }
                using (Stream writer = web.OutputStream) {
                    writer.Write(data, 0, data.Length);
                }
            }

            web.Flush();
        }
예제 #13
0
        protected override void WriteFile(HttpResponseBase response)
        {
            var outPutStream = response.OutputStream;

            using (var streamWriter = new StreamWriter(outPutStream, Encoding.UTF8))
            {
                using (var writer = new CsvWriter(streamWriter))
                {
                    writer.WriteHeader <T>();
                    foreach (var item in _data)
                    {
                        writer.WriteRecord(item);
                    }
                    streamWriter.Flush();
                    response.Flush();
                }
            }
        }
예제 #14
0
        public void CreateAndSendFile(HttpResponseBase Response, string FileName = "Dokument")
        {
            CheckAndCreatePages(); // !important

            if (document.PageCount > 0)
            {
                MemoryStream stream = new MemoryStream();
                document.Save(stream, false);
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Length", stream.Length.ToString());
                Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".pdf");
                Response.BinaryWrite(stream.ToArray());
                Response.Flush();
                stream.Close();
                Response.End();
            }
        }
예제 #15
0
        /// <summary>
        /// Serialises the object that was passed into the constructor to JSON and writes the corresponding JSON to the result stream.
        /// </summary>
        /// <param name="context">The controller context for the current request.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("You're not allowed to do a JSON call through the GET protocol");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JsonSerializerSettings settings = null;
                if (IoC.Resolver.IsRegistered <JsonSerializerSettings>())
                {
                    settings = IoC.Resolver.Resolve <JsonSerializerSettings>();
                }
                response.Write(JsonConvert.SerializeObject(Data, Formatting.None, settings));
                response.Flush();

                //seems sometimes an error is output AFTER the json result, really don't get it :(
                if (!response.TrySkipIisCustomErrors)
                {
                    response.End();
                }
            }
        }
예제 #16
0
 /// <summary>
 /// 网页文件字节流下载
 /// </summary>
 /// <param name="response">Page.Request对象</param>
 /// <param name="bytes">字节流</param>
 /// <param name="fileName">文件名 如:pic.jpg file.mp4 file.csv</param>
 /// <returns>返回是否成功</returns>
 public static bool ResponseFile(HttpResponseBase response, byte[] bytes, string fileName)
 {
     try
     {
         response.AddHeader("Connection", "Keep-Alive");
         response.ContentType = "application/octet-stream";
         //通知浏览器下载文件而不是打开
         response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         response.BinaryWrite(bytes);
         response.Flush();
         response.End();
         response.Close();
     }
     catch
     {
         return(false);
     }
     return(true);
 }
예제 #17
0
파일: WebHelper.cs 프로젝트: liskying/ShCss
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downloadPath"></param>
        /// <param name="server"></param>
        /// <param name="response"></param>
        /// <param name="fileName"></param>
        public static void DownloadFile(this string downloadPath, HttpServerUtilityBase server, HttpResponseBase response, string fileName)
        {
            if (!File.Exists(downloadPath))
            {
                Console.WriteLine("下载的资源不存在!");
                return;
            }
            FileStream iStream = null;

            byte[] buffer;

            try
            {
                var downloadFile = new FileInfo(downloadPath);
                //response.Clear();
                response.ClearHeaders();
                response.ContentType = "application/octet-stream";
                response.AppendHeader("Content-Disposition", "attachment;filename=" + server.UrlEncode(fileName + ".rar"));
                response.AppendHeader("Content-Length", downloadFile.Length.ToString());
                iStream = new FileStream(downloadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var dataToRead = iStream.Length;
                buffer = new byte[dataToRead];
                iStream.Read(buffer, 0, buffer.Count());
                iStream.Close();
                response.BinaryWrite(buffer);
                response.Buffer = true;
                response.Flush();
                response.Close();
                response.End();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
            }
        }
예제 #18
0
        /// <summary>
        /// 根据 datatable 导出文件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="response"></param>
        /// <param name="exportFileName"></param>
        public static void Export(DataTable data, HttpResponseBase response, String exportFileName)
        {
            response.Clear();
            response.Buffer  = true;
            response.Charset = "UTF8";
            response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, Encoding.UTF8).ToString(CultureInfo.InvariantCulture));
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.ContentType     = "application/ms-excel";
            Stream outputStream = DatatableToExcelStream(data);
            var    buffer       = new byte[BufferSize];
            int    bytesRead    = 0;

            while ((bytesRead = outputStream.Read(buffer, 0, BufferSize)) > 0)
            {
                response.OutputStream.Write(buffer, 0, bytesRead);
            }
            outputStream.Close();
            response.Flush();
            response.End();
        }
예제 #19
0
        public void ExportExcel1(List <IExportable> lista, HttpResponseBase Response, string nombreArchivo)
        {
            DataTable dt = ToDataTable(lista);
            var       gv = new GridView();

            gv.DataSource = dt;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=DemoExcel.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.Charset     = "";
            StringWriter   objStringWriter   = new StringWriter();
            HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);

            gv.RenderControl(objHtmlTextWriter);
            Response.Output.Write(objStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
예제 #20
0
        public override void ExecuteResult(ControllerContext context)
        {
            string           fileName = _fileName;
            HttpResponseBase response = context.HttpContext.Response;

            if (File.Exists(_filePath))
            {
                FileStream fs         = null;
                byte[]     fileBuffer = new byte[10240000];//每次读取10240000字节大小的数据,10240000字节(b)=9.765625兆字节(mb)
                try
                {
                    using (fs = File.OpenRead(_filePath))
                    {
                        long totalLength = fs.Length;
                        response.ContentType = "application/octet-stream";
                        response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                        while (totalLength > 0 && response.IsClientConnected)       //持续传输文件
                        {
                            int length = fs.Read(fileBuffer, 0, fileBuffer.Length); //每次读取10240000个字节长度的内容
                            fs.Flush();
                            response.OutputStream.Write(fileBuffer, 0, length);     //写入到响应的输出流
                            response.Flush();                                       //刷新响应
                            totalLength = totalLength - length;
                        }
                        response.Close();//文件传输完毕,关闭相应流
                    }
                }
                catch (Exception ex)
                {
                    response.Write(ex.Message);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();//最后记得关闭文件流
                    }
                }
            }
        }
예제 #21
0
        public override void DownFile(string filePath, string fileName, HttpResponseBase ResponseBase, HttpServerUtilityBase ServerBase)
        {
            try
            {
                filePath = ServerBase.MapPath("~/" + filePath);
                FileStream fs    = new FileStream(filePath, FileMode.Open);
                byte[]     bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                ResponseBase.Charset         = "UTF-8";
                ResponseBase.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                ResponseBase.ContentType     = "application/octet-stream";

                ResponseBase.AddHeader("Content-Disposition", "attachment; filename=" + ServerBase.UrlEncode(fileName));
                ResponseBase.BinaryWrite(bytes);
                ResponseBase.Flush();
                ResponseBase.End();
            }
            catch (Exception ex)
            {
            }
        }
예제 #22
0
        public HttpResponseBase ExportToExcel([FromBody] List <IExportable> lista, HttpServerUtilityBase server, HttpResponseBase response, string nombreArchivo)
        {
            DataTable  dt       = ToDataTable(lista);
            XLWorkbook workbook = new XLWorkbook();

            workbook.Worksheets.Add(dt, "Reporte");

            string myName = server.UrlEncode(nombreArchivo + ".xls");

            response.Clear();
            response.Buffer      = true;
            response.ContentType = "application/vnd.ms-excel";
            //response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", "attachment; filename=" + myName);
            using MemoryStream memoryStream = new MemoryStream();
            workbook.SaveAs(memoryStream);
            memoryStream.Position = 0;
            memoryStream.WriteTo(response.OutputStream);
            response.Flush();
            response.End();
            return(response);
        }
예제 #23
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase _response = context.HttpContext.Response;

            var _data = File.ReadAllBytes(ImagePath);

            _response.Clear();

            _response.ContentType = ImageType(Path.GetExtension(ImagePath));
            _response.Cache.SetMaxAge(TimeSpan.FromDays(365));
            _response.Cache.SetETag(ETag);
            _response.Cache.SetCacheability(HttpCacheability.Public);
            _response.Cache.SetExpires(DateTime.Now.AddYears(1));
            _response.OutputStream.Write(_data, 0, _data.Length);
            _response.Flush();
            _response.End();
        }
예제 #24
0
        public static Task FlushAsync(this HttpResponseBase response)
        {
            if (!response.IsClientConnected)
            {
                return(TaskAsyncHelper.Empty);
            }
#if NET45
            if (response.SupportsAsyncFlush)
            {
                return(Task.Factory.FromAsync((cb, state) => response.BeginFlush(cb, state), ar => response.EndFlush(ar), null));
            }
#endif
            try
            {
                response.Flush();
            }
            catch
            {
            }

            return(TaskAsyncHelper.Empty);
        }
        private static bool ExecuteDownload(HttpResponseBase response, Action callback, bool flush, string filePath, string fileName, Encoding encoding)
        {
            if (response == null || string.IsNullOrEmpty(filePath))
            {
                return(false);
            }

            response.ContentType = MimeHelper.GetMineType(MimeTypeEnum.ALL, true);
            response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode(GetRandomName(filePath, fileName))));
            response.ContentEncoding = encoding;

            if (callback != null)
            {
                callback();
            }
            if (flush)
            {
                response.Flush();
                response.End();
            }
            return(true);
        }
        private static bool WriteFilePortionDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding)
        {
            FileStream fileStream = null;

            try
            {
                return(ExecuteDownload(response, () =>
                {
                    byte[] buffer = new byte[CHUNKSIZE];
                    using (fileStream = File.OpenRead(filePath))
                    {
                        response.AddHeader("Content-Length", fileStream.Length.ToString());

                        long fileSize = fileStream.Length;
                        while (fileSize > 0 && response.IsClientConnected)
                        {
                            int readSize = fileStream.Read(buffer, 0, Convert.ToInt32(CHUNKSIZE));
                            response.OutputStream.Write(buffer, 0, readSize);
                            response.Flush();
                            fileSize = fileSize - readSize;
                        }
                    }
                    response.Close();
                }, false, filePath, fileName, encoding));
            }
            catch
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }

                throw;
            }
        }
예제 #27
0
        protected void SendOuptToClient(HttpContextBase context)
        {
            HttpResponseBase    response = context.Response;
            HttpCachePolicyBase cache    = context.Response.Cache;

            cache.SetETag(_etagCacheKey);
            cache.SetLastModified(_lastModify);
            cache.SetExpires(NetworkTime.Now.AddDays(_durationInDays)); // For HTTP 1.0 browsers
            cache.SetOmitVaryStar(true);
            cache.SetMaxAge(TimeSpan.FromDays(_durationInDays));
            //cache.SetLastModified(NetworkTime.Now);

            cache.SetValidUntilExpires(true);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.VaryByHeaders["Accept-Encoding"] = true;// Tell proxy to cache different versions depending on Accept-Encoding
            response.ContentType = "application/json";
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
        public async Task PushContentToOutputStream(HttpResponseBase response)
        {
            cancellationTokenSource = new CancellationTokenSource();
            var token = cancellationTokenSource.Token;

            await Task.Run(async() =>
            {
                try
                {
                    Log.Info("Start writing to Hystrix outputstream");

                    while (true)
                    {
                        if (token.IsCancellationRequested || response.IsClientConnected == false)
                        {
                            break;
                        }

                        await WriteAllCommandsJsonToOutputStream(response).ConfigureAwait(false);

                        await Task.Delay(pollingInterval, token).ConfigureAwait(false);
                    }
                }
                catch (HttpException e)
                {
                    Log.Error("An error occured in Hystrix outputstream", e);
                }
                finally
                {
                    Log.Info("Flushing and closing Hystrix outputstream");

                    // Close output stream as we are done
                    response.OutputStream.Flush();
                    response.OutputStream.Close();
                    response.Flush();
                }
            }, token).ConfigureAwait(false);
        }
예제 #29
0
        public void ExportData(HttpResponseBase Response, List <IntervalDataVM> intervalData)
        {
            ExcelPackage excel             = new ExcelPackage();
            string       decimalCellFormat = "0.00";

            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");

            using (ExcelRange Rng = workSheet.Cells["E2:E" + intervalData.Count.ToString()])    //Formatting the range for decimal values in excel
            {
                Rng.Style.Numberformat.Format = decimalCellFormat;
            }
            workSheet.Cells[1, 1].LoadFromCollection(intervalData, true);

            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=IntervalData.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
        }
예제 #30
0
        public static void ExportExcel(DataTable dt, HttpResponseBase Response, string FileName)
        {
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold            = true;

                Response.Clear();
                Response.Buffer      = true;
                Response.Charset     = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename= " + FileName + ".xlsx");

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }