Пример #1
0
        public void Upload(HttpCommunicateImpl impl,FileInfo file, Action<string> result, Action<Error> fault,
            string md5, long start, long end, long total, Action<long, long> progress = null)
        {
            this.Result = result;
            this.Fault = fault;
            this.file = file;

            try
            {
                //String uriString = uri.AbsoluteUri;
                //给uri加一个时间戳,停止浏览器缓存
                //采用_time_stamp_" + DateTime.Now.Ticks做为参数名,防止url中有_time_stamp_参数名,
                Uri uri;
                if (UploadUriString.IndexOf('?') == -1)
                {
                    uri = new Uri(UploadUriString + "?_time_stamp_" + DateTime.Now.Ticks + "=1&total=" + total + "&start=" + start + "&end=" + end + "&md5=" + md5);
                }
                else
                {
                    uri = new Uri(UploadUriString + "&_time_stamp_" + DateTime.Now.Ticks + "=1&total=" + total + "&start=" + start + "&end=" + end + "&md5=" + md5);
                }
                //uri = new Uri(UploadUriString);

                request = (HttpWebRequest)WebRequest.Create(uri);
                string boundary = "---------------------------7d429871607fe";
                //HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(uri);
                request.Credentials = CredentialCache.DefaultCredentials;
                request.CookieContainer = impl.Cookies;
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";

                // Build up the post message header
                StringBuilder sb = new StringBuilder();
                sb.Append("--");
                sb.Append(boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition:form-data;name=\"upload\";filename=\"");
                //sb.Append(file.FullName);
                sb.Append(HttpUtility.UrlEncode(file.Name, Encoding.UTF8));
                sb.Append("\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream");
                sb.Append("\r\n");
                sb.Append("\r\n");

                string postHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

                // Build the trailing boundary string as a byte array
                // ensuring the boundary appears on a line by itself
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                byte[] bs = Encoding.ASCII.GetBytes("Content-Disposition: form-data; name=\"total\"\r\n\r\n10");

                //FileStream fileStream = new FileStream(file.Name, FileMode.Open, FileAccess.Read);
                FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);

                request.ContentLength = fileStream.Length + (long)postHeaderBytes.Length + (long)boundaryBytes.Length;   //一定需要长度吗?
                //request.ContentLength = fileStream.Length + (long)postHeaderBytes.Length + (long)boundaryBytes.Length
                //    + bs.Length + (long)boundaryBytes.Length;

                // Write out the trailing boundary

                Stream requestStream = request.GetRequestStream();

                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new Byte[checked((uint)global::System.Math.Min(4096, (int)fileStream.Length))];
                int bytesRead = 0;
                long writeTotal = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    try
                    {
                        writeTotal += bytesRead;
                        if (progress != null)
                        {
                            progress(writeTotal, 0);
                        }
                    }
                    catch (Exception e)
                    {
                    }
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Flush();

                fileStream.Close();
                fileStream = null;

                //bs = Encoding.ASCII.GetBytes("\r\n10");
                //requestStream.Write(bs,
                //    0, bs.Length);

                //requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                //IAsyncResult r = request.BeginGetRequestStream(new AsyncCallback(SetParams), request);

                //Stream stream = request.EndGetRequestStream
                //request.
                request.BeginGetResponse(new AsyncCallback(RespCallback), request);
                //request.BeginGetRequestStream(new AsyncCallback(SetParams), request);
            }
            catch (System.Exception e)
            {
                //如果有异常,表明此次请求失败
                if (Fault != null)
                {
                    //_syncContext.Post((object target) =>
                    //{

                    Error error = new Error();
                    error.code = -2000021;
                    error.message = e.Message;
                    //error.stackTrace = Lin.Core.Utils.ExceptionInfoToString.ADExceptionToString(e);
                    Fault(error);
                    //}, null);
                }
            }
        }
Пример #2
0
        public void Download(HttpCommunicateImpl impl,Uri file, Action<File, long, long, long> result, Action<Error> fault, long p
            , Action<long, long> progress )
        {
            this.progress = progress;
            this.Result = result;
            this.Fault = fault;
            //this.file = file;

            try
            {
                //String uriString = uri.AbsoluteUri;
                //给uri加一个时间戳,停止浏览器缓存
                //采用_time_stamp_" + DateTime.Now.Ticks做为参数名,防止url中有_time_stamp_参数名,
                //Uri uri;
                //if (DownloadUriString.IndexOf('?') == -1)
                //{
                //    uri = new Uri(DownloadUriString + "?_time_stamp_" + DateTime.Now.Ticks + "=1");
                //}
                //else
                //{
                //    uri = new Uri(DownloadUriString + "&_time_stamp_" + DateTime.Now.Ticks + "=1");
                //}
                //uri = new Uri(UploadUriString);

                request = (HttpWebRequest)WebRequest.Create(file);
                request.CookieContainer = impl.Cookies;
                request.Method = "POST";//以POST方式传递数据
                request.ContentType = "application/x-www-form-urlencoded";
                request.AddRange(p);
                //request.AddRange(p, p + 400 * 1024);
                request.BeginGetRequestStream(new AsyncCallback(SetParams), request);
            }
            catch (System.Exception e)
            {
                //如果有异常,表明此次请求失败
                if (Fault != null)
                {
                    //_syncContext.Post((object target) =>
                    //{

                    Error error = new Error();
                    error.code = -2000022;
                    error.message = e.Message;
                    //error.stackTrace = Lin.Core.Utils.ExceptionInfoToString.ADExceptionToString(e);
                        Fault(error);
                    //}, null);
                }
            }
        }
Пример #3
0
 public void Download(HttpCommunicateImpl impl, string file, Action<File, long, long, long> result, Action<Error> fault, long p
    , Action<long, long> progress)
 {
     Uri uri;
     if (DownloadUriString.IndexOf('?') == -1)
     {
         uri = new Uri(DownloadUriString + "?key=" + file + "&_time_stamp_" + DateTime.Now.Ticks + "=1");
     }
     else
     {
         uri = new Uri(DownloadUriString + "&key=" + file + "&_time_stamp_" + DateTime.Now.Ticks + "=1");
     }
     Download(impl,uri, result, fault, p, progress);
 }
Пример #4
0
        public void Request(HttpCommunicateImpl impl,HttpPackage package, Action<Object, IList<Error>> result, Action<Error> fault)
        {
            this.Result = result;
            this._fault = fault;
            this.package = package;

            try
            {
                //string urlPath = package.location;
                //string urlPath = "__http_comm_protocol__";
                //String uriString = uri.AbsoluteUri;
                //给uri加一个时间戳,阻止浏览器缓存
                //采用_time_stamp_" + DateTime.Now.Ticks做为参数名,防止url中有_time_stamp_参数名,
                //if (package.UrlType == Packages.UrlType.RELATIVE)
                //{
                    //if (package.EnableCache)
                    //{
                    //    CommUriString = impl.CommUri.AbsoluteUri;
                    //    if (CommUriString.EndsWith("/") || urlPath.StartsWith("/"))
                    //    {
                    //        uri = new Uri(CommUriString + urlPath);
                    //    }
                    //    else
                    //    {
                    //        uri = new Uri(CommUriString + "/" + urlPath);
                    //    }
                    //}
                    if(!package.EnableCache)
                    {
                        CommUriString = impl.CommUri.AbsoluteUri;

                        if (package.location.StartsWith("/"))
                        {
                            CommUriString += package.location;
                        }
                        else
                        {
                            CommUriString += "/" + package.location;
                        }
                        if (CommUriString.Contains("?"))
                        {
                            uri = new Uri(CommUriString + "&_time_stamp_" + DateTime.Now.Ticks + "=1");
                        }
                        else
                        {
                            uri = new Uri(CommUriString + "?_time_stamp_" + DateTime.Now.Ticks + "=1");
                        }
                    }

                lock (this)
                {
                    request = (HttpWebRequest)WebRequest.Create(uri);

                }
                //Console.WriteLine("proxy:" + request.Proxy);
                //request.Proxy = proxy;
                request.Method = "POST";//以POST方式传递数据
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = impl.Cookies;
                //request.Headers.Add(Constants.HTTP_COMM_PROTOCOL, Constants.HTTP_VERSION);
                //request.Timeout
                //Console.WriteLine("time out:" + request.Timeout);
                //if (package.HasParams)
                {
                    request.BeginGetRequestStream(new AsyncCallback(SetParams), request);
                }
                //else
                {
                    //request.BeginGetResponse(new AsyncCallback(RespCallback), request);
                }
                //r.AsyncWaitHandle.WaitOne();
            }
            catch (System.Exception e)
            {
                //如果有异常,表明此次请求失败
                if (_fault != null)
                {
                    Error error = new Error(0x2000002, "无法连接服务器!", e.StackTrace);
                    Fault(error);
                }
            }
            //catch (Error e) { }
        }
Пример #5
0
        public void Upload(HttpCommunicateImpl impl,FileInfo file, Action<object> result, Action<Error> fault,
            Action<long, long> progress = null)
        {
            this.progress = progress;
            this.Result = result;
            this.Fault = fault;
            this.file = file;
            md5 = getMD5Hash(file.FullName);
            long total = file.Length;

            //一次上传数据大小,以字节为单位
            long step = 1024 * 100;
            long start = 0;
            long end = start + step - 1;
            //先查询 对应 md5值的文件上传情况,然后根据上传的情况  上传还没有上传的数据
            int retryCount = 0;

            long a = 0;

            object lockObj = new object();
            uploadProgressAction = (long a0, long b) =>
            {
                lock (lockObj)
                {
                    a = a0;
                }
            };

            bool isRun = true;
            bool isStop = false;
            bool isError = false;//表示上传是否有错误,true表示有错误,false表示测试错误
            System.Threading.Thread thread = new System.Threading.Thread(new ParameterizedThreadStart(obj =>
            {
                long preP = 0;
                long cp = 0;
                if (progress != null)
                {
                    while (isRun)
                    {
                        try
                        {
                            lock (lockObj)
                            {
                                cp = start + a;
                            }
                            try
                            {
                                if (preP != cp)
                                {
                                    this.progress(cp, total);
                                    preP = cp;
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        catch (Exception) { }
                        System.Threading.Thread.Sleep(50);
                    }
                    try
                    {
                        if (preP != total && !isError)
                        {
                            this.progress(total, total);
                        }
                    }
                    catch (Exception )
                    {
                    }
                }
                isStop = true;
            }));
            thread.IsBackground = true;
            thread.Start();

            while (start < total)
            {
                while (!UploadImpl(impl,md5, start, end, total))
                {
                    retryCount++;
                    if (retryCount > 10 || error.code == HttpCommunicateResult.ABORT_CODE)
                    {
                        isError = true;
                        isRun = false;
                        while (!isStop) { System.Threading.Thread.Sleep(1); }
                        if (fault != null)
                        {
                            fault(error);
                        }
                        return;
                    }
                    System.Threading.Thread.Sleep(1000);
                }
                retryCount = 0;
                start = start + step;
                end = start + step - 1;
                //uploadProgressAction(0, 0);
                if (!this.resultObj.ToString().StartsWith("exile list:"))
                {
                    break;
                }
            }
            //result  startWidth
            //uploadProgressAction(total, total);

            isRun = false;
            while (!isStop) { System.Threading.Thread.Sleep(1); }
            if (result != null)
            {
                result(this.resultObj);
            }
            //(new HttpUpload()).Upload(file, resultObject => { result(resultObject, null); }, fault);
        }
Пример #6
0
 //private object abortObject = new object();
 private bool UploadImpl(HttpCommunicateImpl impl,string md5, long start, long end, long total)
 {
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(HttpCommunicateResult.ABORT_CODE,"上传操作已被取消");
             return false;
         }
     }
     long tick = DateTime.Now.Ticks;
     (new DirectoryInfo(Path.GetTempPath() + "tmp_" + tick + "_" + file.Name)).Create();
     FileInfo tmpFile = new FileInfo(Path.GetTempPath() + "tmp_" + tick + "_" + file.Name + "\\" + file.Name);
     FileStream _in = file.OpenRead();
     FileStream _out = tmpFile.Create();
     _in.Seek(start, SeekOrigin.Begin);
     byte[] bs = new byte[end - start + 1];
     _out.Write(bs, 0, _in.Read(bs, 0, bs.Length));
     _out.Close();
     _in.Close();
     AutoResetEvent are = new AutoResetEvent(false);
     bool isSuccess = true;
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(0x2001000, "上传操作已被取消");
             return false;
         }
         upload = new HttpUpload();
     }
     lock (this)
     {
         upload.Upload(impl,tmpFile, resultObject =>
         {
             resultObj = resultObject;
             are.Set();
         }, error =>
         {
             isSuccess = false;
             this.error = error;
             are.Set();
         }, md5, start, end, total, uploadProgressAction);
     }
     are.WaitOne();
     try
     {
         tmpFile.Delete();
         tmpFile.Directory.Delete();
     }
     catch (Exception) { }
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(HttpCommunicateResult.ABORT_CODE, "上传操作已被取消");
             return false;
         }
     }
     return isSuccess;
 }
Пример #7
0
        public void Download(HttpCommunicateImpl impl,object file, Action<File> result, Action<Error> fault,
            Action<long, long> progress)
        {
            long p = 0;
            long a = 0;
            long total = 0;
            object lockObj = new object();
            downloadProgressAction = (long a0, long b) =>
            {
                lock (lockObj)
                {
                    a = a0;
                }
                total = b;
            };
            bool isRun = true;
            bool isStop = false;
            bool isError = false;//表示上传是否有错误,true表示有错误,false表示测试错误
            System.Threading.Thread thread = new System.Threading.Thread(new ParameterizedThreadStart(obj =>
            {
                long preP = 0;
                long cp = 0;
                if (progress != null)
                {
                    while (isRun)
                    {
                        try
                        {
                            lock (lockObj)
                            {
                                cp = p + a;
                            }
                            if (preP != cp)
                            {
                                progress(cp, total);
                                preP = cp;
                            }
                        }
                        catch (Exception e)
                        {
                        }
                        System.Threading.Thread.Sleep(50);
                    }

                    if (preP != total && progress != null && !isError)
                    {
                        try
                        {
                            progress(total, total);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                isStop = true;
            }));
            thread.IsBackground = true;
            thread.Start();

            int retryCount = 0;
            FileInfo fileInfo = null;// new FileInfo(Lin.Core.ViewModel.Context.Cache.TmpDir.FullName + "\\download_mereg_tmp_" + DateTime.Now.Ticks + "_file_name.tmp");
            FileStream _out = null;// fileInfo.Create();
            while (true)
            {
                retryCount = 0;
                while (!DonwloadImpl(impl,file, p))
                {
                    if (retryCount++ > 10 || error.code == HttpCommunicateResult.ABORT_CODE)
                    {
                        isRun = false;
                        isError = true;
                        while (!isStop) { System.Threading.Thread.Sleep(1); }
                        if (_out != null)
                        {
                            _out.Close();
                        }
                        if (fault != null)
                        {
                            //Error e = new Error();
                            fault(error);
                        }
                        return;
                    }
                    System.Threading.Thread.Sleep(100);
                }
                retryCount = 0;
                if (_out == null)
                {
                    //fileInfo = new FileInfo(Lin.Core.ViewModel2.Context.Cache.TmpDir.FullName + "\\download_mereg_tmp_" + DateTime.Now.Ticks + "_file_name_tmp_" + resultFile.FileName);
                    fileInfo = new FileInfo(Path.GetTempPath() + "\\download_mereg_tmp_" + DateTime.Now.Ticks + "_file_name_tmp_" + resultFile.FileName);
                    _out = fileInfo.Create();
                }
                FileCopy(resultFile.FileInfo, _out);
                resultFile.FileInfo.Delete();
                lock (lockObj)
                {
                    a = 0;
                    p = end + 1;
                }
                if (p >= total - 1)
                {
                    break;
                }
            }
            isRun = false;
            while (!isStop) { System.Threading.Thread.Sleep(1); }
            if (_out != null)
            {
                //_out.Flush();
                //_out.Dispose();
                _out.Close();
            }

            resultFile.FileInfo = fileInfo;
            if (result != null)
            {
                result(resultFile);
            }
        }
Пример #8
0
 //private long total;
 private bool DonwloadImpl(HttpCommunicateImpl impl,object file, long p)
 {
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(HttpCommunicateResult.ABORT_CODE, "上传操作已被取消");
             return false;
         }
     }
     AutoResetEvent are = new AutoResetEvent(false);
     bool flag = false;
     Uri uri = file as Uri;
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(0x2001000, "上传操作已被取消");
             return false;
         }
         download = new HttpDownload();
     }
     if (uri != null)
     {
         lock (this)
         {
             download.Download(impl,uri, (resultObject, start, end, total) =>
             {
                 this.start = start;
                 this.end = end;
                 //this.total = total;
                 resultFile = resultObject;
                 //tmpWarning = null;
                 flag = true;
                 are.Set();
             }, error =>
             {
                 this.error = error;
                 are.Set();
             }, p, downloadProgressAction);
         }
     }
     else
     {
         lock (this)
         {
             download.Download(impl,file as string, (resultObject, start, end, total) =>
             {
                 this.start = start;
                 this.end = end;
                 //this.total = total;
                 resultFile = resultObject;
                 //tmpWarning = null;
                 flag = true;
                 are.Set();
             }, error =>
             {
                 this.error = error;
                 are.Set();
             }, p, downloadProgressAction);
         }
     }
     are.WaitOne();
     lock (this)
     {
         if (isAbort)
         {
             this.error = new Error(HttpCommunicateResult.ABORT_CODE, "上传操作已被取消");
             return false;
         }
     }
     return flag;
 }