// 连Flush带看IsConnected状态 // 如果返回true表示正常,false表示输出流已经切断,没有必要再继续dump了 public static long DumpStream(Stream streamSource, Stream streamTarget, FlushOutput flushOutputMethod) { int nChunkSize = 8192; byte[] bytes = new byte[nChunkSize]; long lLength = 0; while (true) { int n = streamSource.Read(bytes, 0, nChunkSize); if (n != 0) // 2005/6/8 streamTarget.Write(bytes, 0, n); if (flushOutputMethod != null) { if (flushOutputMethod() == false) break; } if (n <= 0) break; lLength += n; //if (n<1000) // break; } return lLength; }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpFile(string strFilename, string strContentType, out string strError) { strError = ""; if (string.IsNullOrEmpty(strFilename)) { strError = "DumpFile() strFilename 参数不应为空"; return(-1); } #if NO // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); #endif this.Response.ContentType = strContentType; FileInfo fi = new FileInfo(strFilename); DateTime lastmodified = fi.LastWriteTimeUtc; this.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified)); // .ToUniversalTime() try { using (Stream stream = File.Open(strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) // 2015/1/12 { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } catch (FileNotFoundException) { strError = "文件 '" + strFilename + "' 不存在"; return(0); } catch (DirectoryNotFoundException) { strError = "文件 '" + strFilename + "' 路径中某一级目录不存在"; return(0); } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); return(-1); } return(1); }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpRssFile(string strRssFile, out string strError) { strError = ""; // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); this.Response.ContentType = "application/rss+xml"; try { // http://stackoverflow.com/questions/904952/whats-causing-session-state-has-created-a-session-id-but-cannot-save-it-becau string sessionId = Session.SessionID; app.ResultsetLocks.LockForRead(strRssFile, 500); try { using (Stream stream = File.Open(strRssFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } finally { app.ResultsetLocks.UnlockForRead(strRssFile); } } catch (System.ApplicationException /*ex*/) { this.Response.ContentType = "text/plain"; this.Response.StatusCode = 503; this.Response.StatusDescription = "相关的XML缓存正在被创建,请稍后重新访问"; return(1); } return(0); }
public static long DumpStream(Stream streamSource, Stream streamTarget, long lLength, FlushOutput flushOutputMethod) { long lWrited = 0; long lThisRead = 0; int nChunkSize = 8192; byte[] bytes = new byte[nChunkSize]; while (true) { long lLeft = lLength - lWrited; if (lLeft > nChunkSize) { lThisRead = nChunkSize; } else { lThisRead = lLeft; } long n = streamSource.Read(bytes, 0, (int)lThisRead); if (n != 0) // 2005/6/8 { streamTarget.Write(bytes, 0, (int)n); } if (flushOutputMethod != null) { if (flushOutputMethod() == false) { break; } } //if (n<nChunkSize) // break; if (n <= 0) { break; } lWrited += n; } return(lWrited); }
public void WriteTo(FlushOutput flushOutputDelegate, CloseOutput closeOutputDelegate, ThreadPriority priority, object to) { if (flushOutputDelegate != null) { flushOutput += flushOutputDelegate; } if (closeOutputDelegate != null) { closeOutput += closeOutputDelegate; } _writeThread = new Thread(FlushThread); _writeThread.Priority = priority; _writeThread.IsBackground = true; _writeThread.Start(to); }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpFile(string strFilename, string strContentType, out string strError) { strError = ""; // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); this.Response.ContentType = strContentType; try { using (Stream stream = File.Open(strFilename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } catch (FileNotFoundException) { strError = "文件 '" + strFilename + "' 不存在"; return(0); } catch (DirectoryNotFoundException) { strError = "文件 '" + strFilename + "' 路径中某一级目录不存在"; return(0); } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); return(-1); } return(1); }
void OutputLogo(string strFileName, string strText) { FileInfo fi = new FileInfo(strFileName); DateTime lastmodified = fi.LastWriteTimeUtc; this.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified)); // .ToUniversalTime() TextInfo info = new TextInfo(); info.FontFace = "Microsoft YaHei"; info.FontSize = 10; info.colorText = Color.Gray; // 文字图片 using (MemoryStream image = ArtText.PaintText( strFileName, strText, info, "center", "100%", "100%", "65%", ImageFormat.Jpeg)) { this.Response.ContentType = "image/jpeg"; this.Response.AddHeader("Content-Length", image.Length.ToString()); //this.Response.AddHeader("Pragma", "no-cache"); //this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); //this.Response.AddHeader("Expires", "0"); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); image.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(image, Response.OutputStream, flushdelegate); } // Response.Flush(); Response.End(); }
// 连Flush带看IsConnected状态 // 如果返回true表示正常,false表示输出流已经切断,没有必要再继续dump了 public static long DumpStream(Stream streamSource, Stream streamTarget, FlushOutput flushOutputMethod) { int nChunkSize = 8192; byte[] bytes = new byte[nChunkSize]; long lLength = 0; while (true) { int n = streamSource.Read(bytes, 0, nChunkSize); if (n != 0) // 2005/6/8 { streamTarget.Write(bytes, 0, n); } if (flushOutputMethod != null) { if (flushOutputMethod() == false) { break; } } if (n <= 0) { break; } lLength += n; //if (n<1000) // break; } return(lLength); }
//OpacApplication app = null; //SessionInfo sessioninfo = null; protected void Page_Load(object sender, EventArgs e) { if (WebUtil.PrepareEnvironment(this, ref app, ref sessioninfo) == false) return; string strError = ""; int nRet = 0; string strBarcode = Request.QueryString["barcode"]; #if NO if (strBarcode.IndexOf("@") != -1) { if (sessioninfo.UserID == strBarcode && string.IsNullOrEmpty(sessioninfo.PhotoUrl) == false) { this.Response.Redirect(this.sessioninfo.PhotoUrl, true); return; } } #endif string strAction = Request.QueryString["action"]; // 获得一般 QR 图像 // getphoto.aspx?action=qri&barcode=????????&width=???&height=??? 其中 width 和 height 参数可以缺省 // 获得读者证号 QR 图像 // getphoto.aspx?action=pqri&barcode=????????&width=???&height=??? 其中 barcode 参数是读者证条码号。要求当前账户具有 getpatrontempid 的权限,而且读者身份只能获取自己的 tempid if (strAction == "qri" || strAction == "pqri") { string strCharset = Request.QueryString["charset"]; string strWidth = Request.QueryString["width"]; string strHeight = Request.QueryString["height"]; string strDisableECI = Request.QueryString["disableECI"]; bool bDisableECI = false; if (string.IsNullOrEmpty(strDisableECI) == false && (strDisableECI.ToLower() == "true" || strDisableECI.ToLower() == "yes" || strDisableECI.ToLower() == "on")) bDisableECI = true; int nWidth = 0; if (string.IsNullOrEmpty(strWidth) == false) { if (Int32.TryParse(strWidth, out nWidth) == false) { strError = "width 参数 '" + strWidth + "' 格式不合法"; goto ERROR1; } } int nHeight = 0; if (string.IsNullOrEmpty(strHeight) == false) { if (Int32.TryParse(strHeight, out nHeight) == false) { strError = "height 参数 '" + strHeight + "' 格式不合法"; goto ERROR1; } } if (strAction == "qri") { nRet = app.OutputQrImage( this.Page, strBarcode, strCharset, nWidth, nHeight, bDisableECI, false, out strError); if (nRet == -1) goto ERROR1; } else if (strAction == "pqri") { // 读者证号二维码 string strCode = ""; // 获得读者证号二维码字符串 nRet = app.GetPatronTempId( // sessioninfo, strBarcode, out strCode, out strError); if (nRet == -1) goto ERROR1; // 把出错信息作为图像返回 nRet = app.OutputQrImage( this.Page, strCode, strCharset, nWidth, nHeight, bDisableECI, false, out strError); if (nRet == -1) goto ERROR1; } this.Response.End(); return; } string strDisplayName = Request.QueryString["displayName"]; string strEncyptBarcode = Request.QueryString["encrypt_barcode"]; // 2012/5/22 // 较新的用法 userid=xxxx 或者 userid=encrypt:xxxx string strUserID = Request.QueryString["userid"]; if (string.IsNullOrEmpty(strUserID) == false) { if (StringUtil.HasHead(strUserID, "encrypt:") == true) { strEncyptBarcode = strUserID.Substring("encrypt:".Length); } else { strBarcode = strUserID; } } string strPhotoPath = ""; // 根据读者证条码号找到头像资源路径 // return: // -1 出错 // 0 没有找到。包括读者记录不存在,或者读者记录里面没有头像对象 // 1 找到 nRet = app.GetReaderPhotoPath( // sessioninfo, strBarcode, strEncyptBarcode, strDisplayName, out strPhotoPath, out strError); if (nRet == -1) goto ERROR1; if (nRet == 0) { this.Response.Redirect(MyWebPage.GetStylePath(app, "nonephoto.png"), true); return; } // TODO: HEAD / if-modify-since等精细处理 // FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); nRet = app.DownloadObject( this, null, strPhotoPath, false, "", out strError); if (nRet == -1) goto ERROR1; Response.End(); return; #if NO ERROR1: Response.Write(strError); Response.End(); return; #endif ERROR1: { // 文字图片 using (MemoryStream image = WebUtil.TextImage( ImageFormat.Gif, strError, Color.Black, Color.Yellow, 10, 300)) { Page.Response.ContentType = "image/gif"; this.Response.AddHeader("Content-Length", image.Length.ToString()); this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); image.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(image, Response.OutputStream, flushdelegate); } Response.Flush(); Response.End(); } }
// return: // -1 出错 // 0 成功 int DumpImageFile( string strImageFile, out string strError) { strError = ""; FileInfo fi = new FileInfo(strImageFile); Page page = this; DateTime lastmodified = fi.LastWriteTimeUtc; string strIfHeader = page.Request.Headers["If-Modified-Since"]; if (String.IsNullOrEmpty(strIfHeader) == false) { DateTime isModifiedSince = DateTimeUtil.FromRfc1123DateTimeString(strIfHeader); // .ToLocalTime(); if (DateTimeUtil.CompareHeaderTime(isModifiedSince, lastmodified) != 0) { // 修改过 } else { // 没有修改过 page.Response.StatusCode = 304; page.Response.SuppressContent = true; return(0); } } page.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified)); // .ToUniversalTime() // string strContentType = API.MimeTypeFrom(ReadFirst256Bytes(strImageFile), ""); string strContentType = PathUtil.MimeTypeFrom(strImageFile); page.Response.ContentType = strContentType; try { using (Stream stream = File.Open(strImageFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { page.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, page.Response.OutputStream, flushdelegate); } } catch (Exception ex) { page.Response.ContentType = "text/plain"; page.Response.StatusCode = 503; page.Response.StatusDescription = ex.Message; return(-1); } return(0); }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpRssFile(string strRssFile, out string strError) { strError = ""; // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); this.Response.ContentType = "application/rss+xml"; try { app.ResultsetLocks.LockForRead(strRssFile, 500); try { Stream stream = File.Open(strRssFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); try { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } finally { stream.Close(); } } finally { app.ResultsetLocks.UnlockForRead(strRssFile); } } catch (System.ApplicationException /*ex*/) { this.Response.ContentType = "text/plain"; this.Response.StatusCode = 503; this.Response.StatusDescription = "相关的XML缓存正在被创建,请稍后重新访问"; return 1; } return 0; }
void GetReportFile(string strUrl, string strFormat) { string strError = ""; if (string.IsNullOrEmpty(app.ReportDir) == true) { strError = "dp2OPAC 尚未配置报表目录"; goto ERROR1; } { // 检查路径的第一级 string strFirstLevel = GetFirstLevel(strUrl); // 观察当前用户是否具有管辖这个分馆的权限 if ( string.IsNullOrEmpty(strFirstLevel) == false && // sessioninfo.Channel != null && ( sessioninfo.GlobalUser == true || StringUtil.IsInList(strFirstLevel, sessioninfo.LibraryCodeList) == true) ) { } else { strError = "当前用户不具备查看分馆 '" + strFirstLevel + "' 的报表的权限"; goto ERROR1; } } #if NO string strLibraryCode = this.TitleBarControl1.SelectedLibraryCode; strLibraryCode = GetDisplayLibraryCode(strLibraryCode); string strReportDir = Path.Combine(app.ReportDir, strLibraryCode); #endif string strReportDir = app.ReportDir; string strFileName = Path.Combine(strReportDir, CutLinkHead(strUrl)); if (strFormat == "excel" || strFormat == "xslx" || strFormat == ".xslx") { strFileName = Path.Combine(Path.GetDirectoryName(strFileName), Path.GetFileNameWithoutExtension(strFileName) + ".xlsx"); } string strOriginFileName = ""; string strRequestExt = ""; // 探测文件是否存在 // patameters: // strRequestFileName 请求的文件名 // strOriginFileName 返回 原始文件名 // strRequestExt 返回 请求的文件扩展名 例如 .html // return: // -1 出错 // 1 成功 int nRet = DetectFileName(strFileName, out strOriginFileName, out strRequestExt, out strError); if (nRet == -1) { this.Response.Write(GetErrorString(strError)); this.Response.End(); return; } // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); string strMime = ""; // string strExt = Path.GetExtension(strFileName); if (string.Compare(strRequestExt, ".rml", true) == 0) { strMime = "text/xml"; } else { PathUtil.GetWindowsMimeType(strRequestExt, out strMime); } if (string.IsNullOrEmpty(strMime) == true) { this.Response.ContentType = "text/html"; } else { this.Response.ContentType = strMime; } this.Response.AddHeader("Content-Disposition", "inline;filename=" + HttpUtility.UrlEncode(Path.GetFileName(strFileName))); string strTempFileName = ""; if (strFileName != strOriginFileName) { string strTempDir = Path.Combine(app.DataDir, "temp"); PathUtil.TryCreateDir(strTempDir); strTempFileName = Path.Combine(strTempDir, "~temp_" + Guid.NewGuid().ToString()); string strCssTemplate = @"BODY { FONT-FAMILY: Microsoft YaHei, Verdana, 宋体; FONT-SIZE: 10pt; } DIV.tabletitle { font-size: 14pt; font-weight: bold; text-align: center; margin: 16pt; color: #444444; } DIV.titlecomment { text-align: center; color: #777777; } DIV.createtime { text-align: center; color: #777777; padding: 4pt; } TABLE.table { font-size: 10pt; /*width: 100%;*/ margin: auto; border-color: #efefef; border-width: 16px; border-style: solid; border-collapse:collapse; background-color: #eeeeee; } TABLE.table TR { border-color: #999999; border-width: 0px; border-bottom-width: 1px; border-style: solid; } TABLE.table THEAD TH { font-weight: bold; white-space:nowrap; } TABLE.table TD, TABLE.table TH { padding: 4pt; padding-left: 10pt; padding-right: 10pt; text-align: left; } %columns% DIV.createtime { text-align: center; font-size: 0.8em; }"; if (string.Compare(strRequestExt, ".html", true) == 0) { nRet = DigitalPlatform.dp2.Statis.Report.RmlToHtml(strOriginFileName, strTempFileName, strCssTemplate, out strError); if (nRet == -1) { goto ERROR1; } } else if (string.Compare(strRequestExt, ".xlsx", true) == 0) { nRet = DigitalPlatform.dp2.Statis.Report.RmlToExcel(strOriginFileName, strTempFileName, out strError); if (nRet == -1) { goto ERROR1; } } strFileName = strTempFileName; } try { using (Stream stream = File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } catch (System.Web.HttpException) { // 2016/1/14 // 因为 Client 端切断通讯 } finally { if (string.IsNullOrEmpty(strTempFileName) == false) { File.Delete(strTempFileName); } } this.Response.OutputStream.Flush(); this.Response.End(); return; ERROR1: this.Response.Write(GetErrorString(strError)); this.Response.End(); }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpRssFile(string strRssFile, out string strError) { strError = ""; // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); this.Response.ContentType = "application/rss+xml"; try { // http://stackoverflow.com/questions/904952/whats-causing-session-state-has-created-a-session-id-but-cannot-save-it-becau string sessionId = Session.SessionID; app.ResultsetLocks.LockForRead(strRssFile, 500); try { using (Stream stream = File.Open(strRssFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } finally { app.ResultsetLocks.UnlockForRead(strRssFile); } } catch (System.ApplicationException /*ex*/) { this.Response.ContentType = "text/plain"; this.Response.StatusCode = 503; this.Response.StatusDescription = "相关的XML缓存正在被创建,请稍后重新访问"; return 1; } return 0; }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpFile(string strFilename, string strContentType, out string strError) { strError = ""; #if NO // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); #endif this.Response.ContentType = strContentType; FileInfo fi = new FileInfo(strFilename); DateTime lastmodified = fi.LastWriteTimeUtc; this.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified)); // .ToUniversalTime() try { using (Stream stream = File.Open(strFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) // 2015/1/12 { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } catch (FileNotFoundException) { strError = "文件 '" + strFilename + "' 不存在"; return 0; } catch (DirectoryNotFoundException) { strError = "文件 '" + strFilename + "' 路径中某一级目录不存在"; return 0; } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); return -1; } return 1; }
// return: // -1 出错 // 0 成功 int DumpImageFile( string strImageFile, out string strError) { strError = ""; FileInfo fi = new FileInfo(strImageFile); Page page = this; DateTime lastmodified = fi.LastWriteTimeUtc; string strIfHeader = page.Request.Headers["If-Modified-Since"]; if (String.IsNullOrEmpty(strIfHeader) == false) { DateTime isModifiedSince = DateTimeUtil.FromRfc1123DateTimeString(strIfHeader); // .ToLocalTime(); if (DateTimeUtil.CompareHeaderTime(isModifiedSince, lastmodified) != 0) { // 修改过 } else { // 没有修改过 page.Response.StatusCode = 304; page.Response.SuppressContent = true; return 0; } } page.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified)); // .ToUniversalTime() string strContentType = API.MimeTypeFrom(ReadFirst256Bytes(strImageFile), ""); page.Response.ContentType = strContentType; try { Stream stream = File.Open(strImageFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); try { page.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, page.Response.OutputStream, flushdelegate); } finally { stream.Close(); } } catch (Exception ex) { page.Response.ContentType = "text/plain"; page.Response.StatusCode = 503; page.Response.StatusDescription = ex.Message; return -1; } return 0; }
// 获得资源。写入文件的版本。特别适用于获得资源,也可用于获得主记录体。 // parameters: // fileTarget 文件。注意在调用函数前适当设置文件指针位置。函数只会在当前位置开始向后写,写入前不会主动改变文件指针。 // strStyleParam 一般设置为"content,data,metadata,timestamp,outputpath"; // input_timestamp 若!=null,则本函数会把第一个返回的timestamp和本参数内容比较,如果不相等,则报错 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 public long GetRes(string strPath, Stream fileTarget, FlushOutput flushOutputMethod, DigitalPlatform.Stop stop, string strStyleParam, byte[] input_timestamp, out string strMetaData, out byte[] baOutputTimeStamp, out string strOutputPath, out string strError) { strError = ""; baOutputTimeStamp = null; strMetaData = ""; strOutputPath = ""; this.ErrorCode = ChannelErrorCode.None; this.ErrorInfo = ""; string strStyle = strStyleParam; if (StringUtil.IsInList("attachment", strStyle) == true) { Debug.Assert(false, "attachment style暂时不能使用"); } // 检查参数 if (StringUtil.IsInList("data", strStyle) == false) { if (fileTarget != null) { strError = "strStyle参数中若不包含data风格,则无法获得数据..."; return -1; } } if (StringUtil.IsInList("data", strStyle) == true) { if (fileTarget == null) { strError = "strStyle参数中若包含data风格,而fileTarget为null,会浪费通讯资源..."; return -1; } } bool bHasMetadataStyle = false; if (StringUtil.IsInList("metadata", strStyle) == true) { bHasMetadataStyle = true; } // string id = ""; byte[] baContent = null; long lStart = 0; int nPerLength = -1; byte[] old_timestamp = null; byte[] timestamp = null; long lTotalLength = -1; for (; ; ) { DoIdle(); // 出让控制权,避免CPU资源耗费过度 if (stop != null && stop.State != 0) { strError = "用户中断"; return -1; } REDO: try { string strMessage = ""; string strPercent = ""; if (lTotalLength != -1) { double ratio = (double)lStart / (double)lTotalLength; strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%"; } if (stop != null) { strMessage = "正在下载 " + Convert.ToString(lStart) + "-" + (lTotalLength == -1 ? "?" : Convert.ToString(lTotalLength)) + " " + strPercent + " " + strPath; stop.SetMessage(strMessage); } IAsyncResult soapresult = this.ws.BeginGetRes(strPath, fileTarget == null ? 0 : lStart, fileTarget == null ? 0 : nPerLength, strStyle, null, null); for (; ; ) { /* try { Application.DoEvents(); // 出让界面控制权 } catch { } // System.Threading.Thread.Sleep(10); // 避免CPU资源过度耗费 */ DoIdle(); // 出让控制权,避免CPU资源耗费过度 bool bRet = soapresult.AsyncWaitHandle.WaitOne(100, false); if (bRet == true) break; } if (this.m_ws == null) { strError = "用户中断"; this.ErrorCode = ChannelErrorCode.RequestCanceled; return -1; } // string strOutputResPath; Result result = this.ws.EndGetRes( out baContent, // out id, out strMetaData, out strOutputPath, out timestamp,soapresult); // 即便不是返回-1,也可能有错误码和错误信息字符串 ConvertErrorCode(result); strError = result.ErrorString; if (result.Value == -1) { if (result.ErrorCode == ErrorCodeValue.NotLogin && this.Container != null) { // return: // -1 error // 0 login failed // 1 login succeed int nRet = this.UiLogin(strPath, out strError); if (nRet == -1 || nRet == 0) { return -1; } goto REDO; } /* ConvertErrorCode(result); strError = result.ErrorString; */ return -1; } if (bHasMetadataStyle == true) { StringUtil.RemoveFromInList("metadata", true, ref strStyle); bHasMetadataStyle = false; } lTotalLength = result.Value; if (StringUtil.IsInList("timestamp", strStyle) == true /* && lTotalLength > 0 * */ ) // 2012/1/11 { if (input_timestamp != null) { if (ByteArray.Compare(input_timestamp, timestamp) != 0) { strError = "下载过程中发现时间戳和input_timestamp参数中的时间戳不一致,下载失败 ..."; return -1; } } if (old_timestamp != null) { if (ByteArray.Compare(old_timestamp, timestamp) != 0) { strError = "下载过程中发现时间戳变化,下载失败 ..."; return -1; } } } old_timestamp = timestamp; if (fileTarget == null) break; // 写入文件 if (StringUtil.IsInList("attachment", strStyle) == true) { Debug.Assert(false, "attachment style暂时不能使用"); /* Attachment attachment = ws.ResponseSoapContext.Attachments[id]; if (attachment == null) { strError = "id为 '" +id+ "' 的attachment在WebService响应中没有找到..."; return -1; } StreamUtil.DumpStream(attachment.Stream, fileTarget); nStart += (int)attachment.Stream.Length; Debug.Assert(attachment.Stream.Length <= result.Value, "每次返回的包尺寸["+Convert.ToString(attachment.Stream.Length)+"]应当小于result.Value["+Convert.ToString(result.Value)+"]"); */ } else { Debug.Assert(StringUtil.IsInList("content", strStyle) == true, "不是attachment风格,就应是content风格"); Debug.Assert(baContent != null, "返回的baContent不能为null"); Debug.Assert(baContent.Length <= result.Value, "每次返回的包尺寸[" + Convert.ToString(baContent.Length) + "]应当小于result.Value[" + Convert.ToString(result.Value) + "]"); fileTarget.Write(baContent, 0, baContent.Length); if (flushOutputMethod != null) { if (flushOutputMethod() == false) { strError = "FlushOutputMethod()用户中断"; return -1; } } lStart += baContent.Length; } if (lStart >= result.Value) break; // 结束 } // end try catch (Exception ex) { /* strError = ConvertWebError(ex); return -1; * */ int nRet = ConvertWebError(ex, out strError); if (nRet == 0) return -1; goto REDO; } } // end of for baOutputTimeStamp = timestamp; this.ClearRedoCount(); return 0; }
//OpacApplication app = null; //SessionInfo sessioninfo = null; protected void Page_Load(object sender, EventArgs e) { if (WebUtil.PrepareEnvironment(this, ref app, ref sessioninfo) == false) { return; } string strError = ""; int nRet = 0; string strBarcode = Request.QueryString["barcode"]; #if NO if (strBarcode.IndexOf("@") != -1) { if (sessioninfo.UserID == strBarcode && string.IsNullOrEmpty(sessioninfo.PhotoUrl) == false) { this.Response.Redirect(this.sessioninfo.PhotoUrl, true); return; } } #endif string strAction = Request.QueryString["action"]; // 获得一般 QR 图像 // getphoto.aspx?action=qri&barcode=????????&width=???&height=??? 其中 width 和 height 参数可以缺省 // 获得读者证号 QR 图像 // getphoto.aspx?action=pqri&barcode=????????&width=???&height=??? 其中 barcode 参数是读者证条码号。要求当前账户具有 getpatrontempid 的权限,而且读者身份只能获取自己的 tempid if (strAction == "qri" || strAction == "pqri") { string strCharset = Request.QueryString["charset"]; string strWidth = Request.QueryString["width"]; string strHeight = Request.QueryString["height"]; string strDisableECI = Request.QueryString["disableECI"]; bool bDisableECI = false; if (string.IsNullOrEmpty(strDisableECI) == false && (strDisableECI.ToLower() == "true" || strDisableECI.ToLower() == "yes" || strDisableECI.ToLower() == "on")) { bDisableECI = true; } int nWidth = 0; if (string.IsNullOrEmpty(strWidth) == false) { if (Int32.TryParse(strWidth, out nWidth) == false) { strError = "width 参数 '" + strWidth + "' 格式不合法"; goto ERROR1; } } int nHeight = 0; if (string.IsNullOrEmpty(strHeight) == false) { if (Int32.TryParse(strHeight, out nHeight) == false) { strError = "height 参数 '" + strHeight + "' 格式不合法"; goto ERROR1; } } if (strAction == "qri") { nRet = app.OutputQrImage( this.Page, strBarcode, strCharset, nWidth, nHeight, bDisableECI, false, out strError); if (nRet == -1) { goto ERROR1; } } else if (strAction == "pqri") { // 读者证号二维码 string strCode = ""; // 获得读者证号二维码字符串 nRet = app.GetPatronTempId( // sessioninfo, strBarcode, out strCode, out strError); if (nRet == -1) { goto ERROR1; // 把出错信息作为图像返回 } nRet = app.OutputQrImage( this.Page, strCode, strCharset, nWidth, nHeight, bDisableECI, false, out strError); if (nRet == -1) { goto ERROR1; } } this.Response.End(); return; } string strDisplayName = Request.QueryString["displayName"]; string strEncyptBarcode = Request.QueryString["encrypt_barcode"]; // 2012/5/22 // 较新的用法 userid=xxxx 或者 userid=encrypt:xxxx string strUserID = Request.QueryString["userid"]; if (string.IsNullOrEmpty(strUserID) == false) { if (StringUtil.HasHead(strUserID, "encrypt:") == true) { strEncyptBarcode = strUserID.Substring("encrypt:".Length); } else { strBarcode = strUserID; } } string strPhotoPath = ""; // 根据读者证条码号找到头像资源路径 // return: // -1 出错 // 0 没有找到。包括读者记录不存在,或者读者记录里面没有头像对象 // 1 找到 nRet = app.GetReaderPhotoPath( // sessioninfo, strBarcode, strEncyptBarcode, strDisplayName, out strPhotoPath, out strError); if (nRet == -1) { goto ERROR1; } if (nRet == 0) { this.Response.Redirect(MyWebPage.GetStylePath(app, "nonephoto.png"), true); return; } // TODO: HEAD / if-modify-since等精细处理 // FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); nRet = app.DownloadObject( this, null, strPhotoPath, false, "", out strError); if (nRet == -1) { goto ERROR1; } Response.End(); return; #if NO ERROR1: Response.Write(strError); Response.End(); return; #endif ERROR1: { // 文字图片 using (MemoryStream image = WebUtil.TextImage( ImageFormat.Gif, strError, Color.Black, Color.Yellow, 10, 300)) { Page.Response.ContentType = "image/gif"; this.Response.AddHeader("Content-Length", image.Length.ToString()); this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); image.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(image, Response.OutputStream, flushdelegate); } Response.Flush(); Response.End(); } }
void GetReportFile(string strUrl, string strFormat) { string strError = ""; if (string.IsNullOrEmpty(app.ReportDir) == true) { strError = "dp2OPAC 尚未配置报表目录"; goto ERROR1; } { // 检查路径的第一级 string strFirstLevel = GetFirstLevel(strUrl); // 观察当前用户是否具有管辖这个分馆的权限 if ( string.IsNullOrEmpty(strFirstLevel) == false && // sessioninfo.Channel != null && ( sessioninfo.GlobalUser == true || StringUtil.IsInList(strFirstLevel, sessioninfo.LibraryCodeList) == true) ) { } else { strError = "当前用户不具备查看分馆 '" + strFirstLevel + "' 的报表的权限"; goto ERROR1; } } #if NO string strLibraryCode = this.TitleBarControl1.SelectedLibraryCode; strLibraryCode = GetDisplayLibraryCode(strLibraryCode); string strReportDir = Path.Combine(app.ReportDir, strLibraryCode); #endif string strReportDir = app.ReportDir; string strFileName = Path.Combine(strReportDir, CutLinkHead(strUrl)); if (strFormat == "excel" || strFormat == "xslx" || strFormat == ".xslx") { strFileName = Path.Combine(Path.GetDirectoryName(strFileName), Path.GetFileNameWithoutExtension(strFileName) + ".xlsx"); } string strOriginFileName = ""; string strRequestExt = ""; // 探测文件是否存在 // patameters: // strRequestFileName 请求的文件名 // strOriginFileName 返回 原始文件名 // strRequestExt 返回 请求的文件扩展名 例如 .html // return: // -1 出错 // 1 成功 int nRet = DetectFileName(strFileName, out strOriginFileName, out strRequestExt, out strError); if (nRet == -1) { this.Response.Write(GetErrorString(strError)); this.Response.End(); return; } // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); string strMime = ""; // string strExt = Path.GetExtension(strFileName); if (string.Compare(strRequestExt, ".rml", true) == 0) strMime = "text/xml"; else PathUtil.GetWindowsMimeType(strRequestExt, out strMime); if (string.IsNullOrEmpty(strMime) == true) this.Response.ContentType = "text/html"; else this.Response.ContentType = strMime; this.Response.AddHeader("Content-Disposition", "inline;filename=" + HttpUtility.UrlEncode(Path.GetFileName(strFileName))); string strTempFileName = ""; if (strFileName != strOriginFileName) { string strTempDir = Path.Combine(app.DataDir, "temp"); PathUtil.CreateDirIfNeed(strTempDir); strTempFileName = Path.Combine(strTempDir, "~temp_" + Guid.NewGuid().ToString()); string strCssTemplate = @"BODY { FONT-FAMILY: Microsoft YaHei, Verdana, 宋体; FONT-SIZE: 10pt; } DIV.tabletitle { font-size: 14pt; font-weight: bold; text-align: center; margin: 16pt; color: #444444; } DIV.titlecomment { text-align: center; color: #777777; } DIV.createtime { text-align: center; color: #777777; padding: 4pt; } TABLE.table { font-size: 10pt; /*width: 100%;*/ margin: auto; border-color: #efefef; border-width: 16px; border-style: solid; border-collapse:collapse; background-color: #eeeeee; } TABLE.table TR { border-color: #999999; border-width: 0px; border-bottom-width: 1px; border-style: solid; } TABLE.table THEAD TH { font-weight: bold; white-space:nowrap; } TABLE.table TD, TABLE.table TH { padding: 4pt; padding-left: 10pt; padding-right: 10pt; text-align: left; } %columns% DIV.createtime { text-align: center; font-size: 0.8em; }"; if (string.Compare(strRequestExt, ".html", true) == 0) { nRet = DigitalPlatform.dp2.Statis.Report.RmlToHtml(strOriginFileName, strTempFileName, strCssTemplate, out strError); if (nRet == -1) goto ERROR1; } else if (string.Compare(strRequestExt, ".xlsx", true) == 0) { nRet = DigitalPlatform.dp2.Statis.Report.RmlToExcel(strOriginFileName, strTempFileName, out strError); if (nRet == -1) goto ERROR1; } strFileName = strTempFileName; } try { using (Stream stream = File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } } catch (System.Web.HttpException) { // 2016/1/14 // 因为 Client 端切断通讯 } finally { if (string.IsNullOrEmpty(strTempFileName) == false) { File.Delete(strTempFileName); } } this.Response.OutputStream.Flush(); this.Response.End(); return; ERROR1: this.Response.Write(GetErrorString(strError)); this.Response.End(); }
public static long DumpStream(Stream streamSource, Stream streamTarget, long lLength, FlushOutput flushOutputMethod) { long lWrited = 0; long lThisRead = 0; int nChunkSize = 8192; byte[] bytes = new byte[nChunkSize]; while (true) { long lLeft = lLength - lWrited; if (lLeft > nChunkSize) lThisRead = nChunkSize; else lThisRead = lLeft; long n = streamSource.Read(bytes, 0, (int)lThisRead); if (n != 0) // 2005/6/8 streamTarget.Write(bytes, 0, (int)n); if (flushOutputMethod != null) { if (flushOutputMethod() == false) break; } //if (n<nChunkSize) // break; if (n <= 0) break; lWrited += n; } return lWrited; }
// return: // -1 出错 // 0 成功 // 1 暂时不能访问 int DumpFile(string strFilename, string strContentType, out string strError) { strError = ""; // 不让浏览器缓存页面 this.Response.AddHeader("Pragma", "no-cache"); this.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); this.Response.AddHeader("Expires", "0"); this.Response.ContentType = strContentType; try { Stream stream = File.Open(strFilename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); try { this.Response.AddHeader("Content-Length", stream.Length.ToString()); FlushOutput flushdelegate = new FlushOutput(MyFlushOutput); stream.Seek(0, SeekOrigin.Begin); StreamUtil.DumpStream(stream, this.Response.OutputStream, flushdelegate); } finally { stream.Close(); } } catch (FileNotFoundException) { strError = "文件 '" + strFilename + "' 不存在"; return 0; } catch (DirectoryNotFoundException) { strError = "文件 '" + strFilename + "' 路径中某一级目录不存在"; return 0; } catch (Exception ex) { strError = ex.Message; return -1; } return 1; }
public void WriteTo(FlushOutput flushOutputDelegate, CloseOutput closeOutputDelegate, ThreadPriority priority, object to) { if (flushOutputDelegate != null) flushOutput += flushOutputDelegate; if (closeOutputDelegate != null) closeOutput += closeOutputDelegate; _writeThread = new Thread(FlushThread); _writeThread.Priority = priority; _writeThread.IsBackground = true; _writeThread.Start(to); }
// 下载对象资源 // return: // -1 出错 // 0 304返回 // 1 200返回 public int DownloadObject(System.Web.UI.Page Page, FlushOutput flushOutputMethod, RmsChannelCollection channels, string strPath, bool bSaveAs, out string strError) { strError = ""; WebPageStop stop = new WebPageStop(Page); RmsChannel channel = channels.GetChannel(this.WsUrl); if (channel == null) { strError = "GetChannel() Error..."; return -1; } // strPath = boards.GetCanonicalUri(strPath); // 获得资源。写入文件的版本。特别适用于获得资源,也可用于获得主记录体。 // parameters: // fileTarget 文件。注意在调用函数前适当设置文件指针位置。函数只会在当前位置开始向后写,写入前不会主动改变文件指针。 // strStyleParam 一般设置为"content,data,metadata,timestamp,outputpath"; // input_timestamp 若!=null,则本函数会把第一个返回的timestamp和本参数内容比较,如果不相等,则报错 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 string strMetaData = ""; string strOutputPath; byte[] baOutputTimeStamp = null; // 获得媒体类型 long lRet = channel.GetRes( strPath, null, // Response.OutputStream, stop, "metadata", null, // byte [] input_timestamp, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { strError = "GetRes() '"+strPath+"' (for metadata) Error : " + strError; return -1; } if (Page.Response.IsClientConnected == false) return -1; // 取metadata中的mime类型信息 Hashtable values = StringUtil.ParseMetaDataXml(strMetaData, out strError); if (values == null) { strError = "ParseMedaDataXml() Error :" + strError; return -1; } string strLastModifyTime = (string)values["lastmodifytime"]; if (String.IsNullOrEmpty(strLastModifyTime) == false) { DateTime lastmodified = DateTime.Parse(strLastModifyTime); string strIfHeader = Page.Request.Headers["If-Modified-Since"]; if (String.IsNullOrEmpty(strIfHeader) == false) { DateTime isModifiedSince = DateTimeUtil.FromRfc1123DateTimeString(strIfHeader).ToLocalTime(); if (isModifiedSince != lastmodified) { // 修改过 } else { // 没有修改过 Page.Response.StatusCode = 304; Page.Response.SuppressContent = true; return 0; } } Page.Response.AddHeader("Last-Modified", DateTimeUtil.Rfc1123DateTimeString(lastmodified.ToUniversalTime())); /* Page.Response.Cache.SetLastModified(lastmodified); Page.Response.Cache.SetCacheability(HttpCacheability.Public); * */ } string strMime = (string)values["mimetype"]; string strClientPath = (string)values["localpath"]; if (strClientPath != "") strClientPath = PathUtil.PureName(strClientPath); // TODO: 如果是非image/????类型,都要加入content-disposition // 是否出现另存为对话框 if (bSaveAs == true) { string strEncodedFileName = HttpUtility.UrlEncode(strClientPath, Encoding.UTF8); Page.Response.AddHeader("content-disposition", "attachment; filename=" + strEncodedFileName); } /* Page.Response.AddHeader("Accept-Ranges", "bytes"); Page.Response.AddHeader("Last-Modified", "Wed, 21 Nov 2007 07:10:54 GMT"); * */ // 用 text/plain IE XML 搜索google // http://support.microsoft.com/kb/329661 // http://support.microsoft.com/kb/239750/EN-US/ /* To use this fix, you must add the following registry value to the key listed below: Key: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings Value name: IsTextPlainHonored Value type: DWORD Value data: HEX 0x1 * */ /* Page.Response.CacheControl = "no-cache"; // 如果不用此句,text/plain会被当作xml文件打开 Page.Response.AddHeader("Pragma", "no-cache"); Page.Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // Page.Response.AddHeader("Cache-Control", "public"); Page.Response.AddHeader("Expires", "0"); Page.Response.AddHeader("Content-Transfer-Encoding", "binary"); * */ // 设置媒体类型 if (strMime == "text/plain") strMime = "text"; Page.Response.ContentType = strMime; string strSize = (string)values["size"]; if (String.IsNullOrEmpty(strSize) == false) { Page.Response.AddHeader("Content-Length", strSize); } if (Page.Response.IsClientConnected == false) return -1; // 传输数据 lRet = channel.GetRes( strPath, Page.Response.OutputStream, flushOutputMethod, stop, "content,data", null, // byte [] input_timestamp, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { strError = "GetRes() (for res) Error : " + strError; return -1; } return 1; }