Пример #1
0
        public int DownloadObject0(System.Web.UI.Page Page,
            LibraryChannel channel,
            string strPath,
            bool bSaveAs,
            string strStyle,
            out string strError)
        {
            strError = "";

            WebPageStop stop = new WebPageStop(Page);

            // 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;
            byte[] baContent = null;
            // 只获得媒体类型
            long lRet = channel.GetRes(
                stop,
                strPath,
                0,
                0,
                "metadata",
                out baContent,
                out strMetaData,
                out strOutputPath,
                out baOutputTimeStamp,
                out strError);
            if (lRet == -1)
            {
                if (StringUtil.IsInList("hitcount", strStyle))
                {
                    OutputImage(Page,
                        Color.FromArgb(100, Color.Red),
                        "?");
                    return 1;
                }

                if (channel.ErrorCode == ErrorCode.AccessDenied)
                {
                    // 权限不够
                    return -1;
                }

                strError = "GetRes() (for metadata) Error : " + strError;
                return -1;
            }

            if (Page.Response.IsClientConnected == false)
                return -1;

            // 取 metadata 中的 mime 类型信息
            Hashtable values = StringUtil.ParseMedaDataXml(strMetaData,
                out strError);
            if (values == null)
            {
                strError = "ParseMedaDataXml() Error :" + strError;
                return -1;
            }

            if (StringUtil.IsInList("hitcount", strStyle))
            {
                string strReadCount = (string)values["readCount"];
                if (string.IsNullOrEmpty(strReadCount) == true)
                    strReadCount = "?";
                OutputImage(Page,
                    Color.FromArgb(200, Color.DarkGreen),
                    strReadCount);
                return 1;
            }
#if NO
            RETURN_IMAGE:
            if (StringUtil.IsInList("hitcount", strStyle))
            {
                string strReadCount = (string)values["readCount"];
                if (string.IsNullOrEmpty(strReadCount) == true)
                    strReadCount = "?";

                // 文字图片
                using (MemoryStream image = ArtText.BuildArtText(
                    strReadCount,
                    "Microsoft YaHei",
                    (float)12,
                                FontStyle.Regular,
                Color.Black,
                Color.White,
                Color.Gray,
                ArtEffect.None,
                ImageFormat.Jpeg,
                100))
                {
                    Page.Response.ContentType = "image/jpeg";
                    Page.Response.AddHeader("Content-Length", image.Length.ToString());

                    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("Expires", "0");

                    // FlushOutput flushdelegate = new FlushOutput(MyFlushOutput);

                    image.Seek(0, SeekOrigin.Begin);
                    StreamUtil.DumpStream(image, Page.Response.OutputStream/*, flushdelegate*/);

                }
                Page.Response.Flush();
                return 1;
            }
#endif

            string strLastModifyTime = (string)values["lastmodifytime"];
            if (String.IsNullOrEmpty(strLastModifyTime) == false)
            {
                DateTime lastmodified = DateTime.Parse(strLastModifyTime).ToUniversalTime();
                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()
                /*
                                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(
                stop,
                strPath,
                Page.Response.OutputStream,
                "content,data,incReadCount",
                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;
        }
Пример #2
0
        public static int SaveUploadFile(
            System.Web.UI.Page page,
            LibraryChannel channel,
            string strXmlRecPath,
            string strFileID,
            string strResTimeStamp,
            HttpPostedFile postedFile,
            int nLogoLimitW,
            int nLogoLimitH,
            out string strError)
        {
            strError = "";

            if (String.IsNullOrEmpty(postedFile.FileName) == true
                && postedFile.ContentLength == 0)
            {
                return 0;	// 没有必要保存
            }

            WebPageStop stop = new WebPageStop(page);

            string strResPath = strXmlRecPath + "/object/" + strFileID;

            string strLocalFileName = Path.GetTempFileName();
            try
            {
                using (Stream t = File.Create(strLocalFileName))
                {
                    // 缩小尺寸
                    int nRet = GraphicsUtil.ShrinkPic(postedFile.InputStream,
                            postedFile.ContentType,
                            nLogoLimitW,
                            nLogoLimitH,
                            true,
                            t,
                            out strError);
                    if (nRet == -1)
                        return -1;
                    if (nRet == 0)  // 没有必要缩放
                    {
                        postedFile.InputStream.Seek(0, SeekOrigin.Begin);
                        StreamUtil.DumpStream(postedFile.InputStream, t);
                    }
                }

                // t.Close();


                // 检测文件尺寸
                FileInfo fi = new FileInfo(strLocalFileName);

                if (fi.Exists == false)
                {
                    strError = "文件 '" + strLocalFileName + "' 不存在...";
                    return -1;
                }

                string[] ranges = null;

                if (fi.Length == 0)
                { // 空文件
                    ranges = new string[1];
                    ranges[0] = "";
                }
                else
                {
                    string strRange = "";
                    strRange = "0-" + Convert.ToString(fi.Length - 1);

                    // 按照100K作为一个chunk
                    ranges = RangeList.ChunkRange(strRange,
                        100 * 1024);
                }

                byte[] timestamp = ByteArray.GetTimeStampByteArray(strResTimeStamp);
                byte[] output_timestamp = null;

                // 2007/12/13 
                string strLastModifyTime = DateTime.UtcNow.ToString("u");

                string strLocalPath = postedFile.FileName;

                // page.Response.Write("<br/>正在保存" + strLocalPath);

            REDOWHOLESAVE:
                string strWarning = "";

                for (int j = 0; j < ranges.Length; j++)
                {
                REDOSINGLESAVE:

                    // Application.DoEvents();	// 出让界面控制权

                    if (stop.State != 0)
                    {
                        strError = "用户中断";
                        goto ERROR1;
                    }

                    string strWaiting = "";
                    if (j == ranges.Length - 1)
                        strWaiting = " 请耐心等待...";

                    string strPercent = "";
                    RangeList rl = new RangeList(ranges[j]);
                    if (rl.Count >= 1)
                    {
                        double ratio = (double)((RangeItem)rl[0]).lStart / (double)fi.Length;
                        strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%";
                    }

                    if (stop != null)
                        stop.SetMessage("正在上载 " + ranges[j] + "/"
                            + Convert.ToString(fi.Length)
                            + " " + strPercent + " " + strLocalFileName + strWarning + strWaiting);

                    // page.Response.Write(".");	// 防止前端因等待过久而超时
                    long lRet = channel.SaveResObject(
stop,
strResPath,
                        strLocalFileName,
                        strLocalPath,
                        postedFile.ContentType, 
                        ranges[j],
j == ranges.Length - 1 ? true : false,	// 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间
timestamp,
out output_timestamp,
out strError);

                    /*
                    long lRet = channel.DoSaveResObject(strResPath,
                        strLocalFileName,
                        strLocalPath,
                        postedFile.ContentType,
                        strLastModifyTime,
                        ranges[j],
                        j == ranges.Length - 1 ? true : false,	// 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间
                        timestamp,
                        out output_timestamp,
                        out strError);
                     * */

                    timestamp = output_timestamp;

                    // DomUtil.SetAttr(node, "__timestamp",	ByteArray.GetHexTimeStampString(timestamp));

                    strWarning = "";

                    if (lRet == -1)
                    {
                        if (channel.ErrorCode == CirculationClient.localhost.ErrorCode.TimestampMismatch)
                        {

                            timestamp = new byte[output_timestamp.Length];
                            Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length);
                            strWarning = " (时间戳不匹配, 自动重试)";
                            if (ranges.Length == 1 || j == 0)
                                goto REDOSINGLESAVE;
                            goto REDOWHOLESAVE;
                        }

                        goto ERROR1;
                    }


                }


                return 1;	// 已经保存
            ERROR1:
                return -1;
            }
            finally
            {
                // 不要忘记删除临时文件
                File.Delete(strLocalFileName);
            }
        }