私人記錄代碼緩存
try { int pid = int.Parse(request.QueryString["pid"]); int fid = int.Parse(request.QueryString["fid"]); m_log.Debug(string.Format("Download PackageID={0}-------------------------FileID={1}", pid, fid)); FileDB fdb = new FileDB(); PackageDB pdb = new PackageDB(); StorageDB sdb = new StorageDB(); Storage storage = sdb.GetStorageByID(package.StorageID); int index = pid / 2000; string fullPath = string.Format("{0}\\Data{1}\\{2}\\{3}", storage.RootPath, index, package.DBID, fileinfo.Path); if (System.IO.File.Exists(fullPath)) { FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); long total = fs.Length; string str = request.Headers.Get("Range"); int start = str.IndexOf('='); str = str.Substring(start + 1, str.Length - start - 2); long len = long.Parse(str); fs.Seek(len, SeekOrigin.Begin); long left = total - len; long datalen = Math.Min(1024 * 1024, left); byte[] data = new byte[datalen]; int size = fs.Read(data, 0, data.Length); fs.Close(); fs.Dispose(); response.ContentType = "application/octet-stream"; response.Headers.Add("Total-Length", total.ToString()); response.BinaryWrite(data); } else { m_log.Error(string.Format("Download file {0} not exist fid={1}", fullPath, fid.ToString())); }
public bool Upload(FileAddRet arg, int pid, string filefullpath, Address adr, WaitHandle[] handlers) { string address = string.Format("http://{0}:{1}/Upload", adr.ServerName, adr.Port); // 要上傳的文件 FileStream fs = new FileStream(filefullpath, FileMode.Open, FileAccess.Read); long total = fs.Length; fs.Seek(arg.CurrentSize, SeekOrigin.Begin); long offset = arg.CurrentSize; //時間戳 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //請求頭部信息 StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("file"); sb.Append("\"; filename=\""); sb.Append(string.Format("{0}_{1}", pid, arg.ID)); sb.Append("\""); sb.Append("\r\n"); sb.Append("Content-Type: "); sb.Append("application/octet-stream"); sb.Append("\r\n"); sb.Append("\r\n"); string strPostHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); byte[] buffer = new byte[m_bufferLength]; int size = fs.Read(buffer, 0, m_bufferLength); while (size > 0 && WaitHandle.WaitAny(handlers, 0) == WaitHandle.WaitTimeout) { // 根據uri建立HttpWebRequest對象 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address)); //用於聯繫intnert資源的請求方式、默認GET httpReq.Method = "POST"; httpReq.ProtocolVersion = HttpVersion.Version10; //對發送的數據不使用緩存 httpReq.AllowWriteStreamBuffering = false; //設置得到響應的超時時間(300秒) httpReq.Timeout = 30000; httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary; long length = size + postHeaderBytes.Length + boundaryBytes.Length; long fileLength = fs.Length; httpReq.ContentLength = length; Stream postStream = httpReq.GetRequestStream(); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(buffer, 0, size); postStream.Write(boundaryBytes, 0, boundaryBytes.Length); postStream.Close(); offset += size; size = fs.Read(buffer, 0, m_bufferLength); //獲取服務器端的響應 HttpWebResponse Respon = (HttpWebResponse)httpReq.GetResponse(); Stream st = Respon.GetResponseStream(); StreamReader str = new StreamReader(st); //讀取服務器端返回的消息 String ReturnString = str.ReadLine(); m_log.Debug(ReturnString + filefullpath); //發送完成debug st.Close(); str.Close(); //傳輸進度事件 int progress = (int)((double)offset / (double)total * 100); NoticeUploadProgress(progress); } fs.Close(); fs.Dispose(); if (size > 0) return false; else return true; } public bool Download(int pid, int fid, string filefullpath, Address adr, WaitHandle[] handlers) { try { m_log.Debug(string.Format("Download pid={0}, fid={1}, local path={2}", pid, fid, filefullpath)); string address = string.Format("http://{0}:{1}/Download?pid={2}&fid={3}", adr.ServerName, adr.Port, pid, fid); string fileDirectory = Path.GetDirectoryName(filefullpath); if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } long current = 0; long totalLength = 0; while (WaitHandle.WaitAny(handlers, 0) == WaitHandle.WaitTimeout) { using (FileStream fs = new FileStream(filefullpath, FileMode.Append, FileAccess.Write, FileShare.None, 1048576, FileOptions.WriteThrough)) { totalLength = fs.Length; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(address)); request.ProtocolVersion = HttpVersion.Version10; request.Timeout = 30000; request.AddRange((int)fs.Length); //m_log.Debug("addrange len=" + fs.Length.ToString()); Stream ns = request.GetResponse().GetResponseStream(); //m_log.Debug("GetResponse"); long contentLength = request.GetResponse().ContentLength; //m_log.Debug("contentlen=" + contentLength.ToString()); //long contentLength = long.Parse(request.GetResponse().Headers.Get("Content-Length")); if (contentLength == 0) { //m_log.Debug("contentlen=0 return"); current = fs.Length; break; } totalLength = long.Parse(request.GetResponse().Headers.Get("Total-Length")); //m_log.Debug("totallen=" + totalLength); byte[] buffer = new byte[contentLength]; int length = ns.Read(buffer, 0, buffer.Length); //m_log.Debug("write file len=" + length.ToString()); while (length > 0) { fs.Write(buffer, 0, length); fs.Flush(); length = ns.Read(buffer, 0, buffer.Length); //m_log.Debug("write"); } //m_log.Debug("write done"); current = fs.Length; fs.Close(); ns.Close(); int progress = (int)((double)current / (double)totalLength * 100); NoticeDownloadProgress(progress); } } if (current < totalLength) { //m_log.Debug("current <totalLength return false"); return false; } else { //m_log.Debug("down finish"); return true; } } catch (Exception ex) { m_log.Error(ex); return false; } }