C# private Upload DownLoad File

私人记录代码

 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;
            }
        }
 
  

 

 
 

 

转载于:https://www.cnblogs.com/zebra-bin/p/11236947.html

Python网络爬虫与推荐算法新闻推荐平台:网络爬虫:通过Python实现新浪新闻的爬取,可爬取新闻页面上的标题、文本、图片、视频链接(保留排版) 推荐算法:权重衰减+标签推荐+区域推荐+热点推荐.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值