目前相对稳定的下载上传的方法(WebClient )(异步与进度)

时间:2024-09-29 17:31:14

使用webdav (WebClient ) 操作另外还有其他方法:
上传操作

/// <summary>
        /// 上传大文件使用的方法
        /// </summary>
        /// <param name="FileName">文件当前路径</param>
        /// <returns>msg.ReturnStr 返回上传文件地址</returns>
        public  CommMsg   UploadByBigFileweb(string FileName)// CommMsg UploadByBigFileweb(string FileName)
        {
            string ThisFenqu = DateTime.Now.ToString("yyyy-MM");
            string DirPath = WebDirAll + $"{ThisFenqu}/";
            Uri myURi = new System.Uri(DirPath + Path.GetFileName(FileName));
            // 创建WebClient实例
            WebClient myWebClient = new WebClient();
            //访问权限设置
            myWebClient.Credentials = new NetworkCredential(WebUser, WebPw);

            try
            {
                FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] postArray = br.ReadBytes((int)fs.Length);
                myWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressChangd);
                myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadeCompleteZd);

                myWebClient.UploadFileAsync(myURi,"PUT", FileName);//必须加入条件PUT

                if (FrmPreB == null)
                {
                    FrmPreB = new FrmPressBar();
                }
                FrmPreB.Show();
                FrmPreB.SetFileName = FileName;
                FrmPreB.SetPressMaxValue = (int)fs.Length;
                //while (!IsUploadSuc)
                //{
                //    await Task.Delay(1000);

                //} 
                msg.ReturnStr = ThisFenqu + "/" + Path.GetFileName(FileName);
                msg.Success = true; 
            }
            catch (WebException errMsg)
            {
                if (errMsg.Message.Contains("(409)"))//如果失败就创建文件夹后才重新操作
                {
                    CommMsg msgThis = new CommMsg();
                    msgThis = CreateDir(DirPath);
                    if (msg.Success)
                    {
                        UploadByweb(FileName);
                    }
                    else
                    {
                        msg.Success = false;
                        msg.ErrMsg = "文件夹创建失败";
                    }
                }
                else
                {
                    msg.Success = false;
                    msg.ErrMsg = errMsg.Message;
                }
            }
            return msg;
        }

/// <summary>
        /// 上传结束了
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>

        private void UploadeCompleteZd(object Sender, UploadFileCompletedEventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 上传进度操作
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        private void UploadProgressChangd(object Sender, UploadProgressChangedEventArgs e)
        {
            if (this.IsHandleCreated)
            {
                this.SetFilelengthValue = (int)e.TotalBytesToSend;
                this.SetFilelengthThisValue = (int)e.BytesSent;
            }
        }

        /// <summary>
        /// 两秒以后开启操作(如果在frm界面上操作的话)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            OutMsg =  UploadByBigFileweb(FileNameAdd);
            timer1.Stop();
        }


下载操作

  /// <summary>
        /// 下载数据直接保存到地址(外部下载使用)
        /// </summary>
        /// <param name="FileNameAndYearMonth">服务器地址</param>
        /// <param name="SetPath">设置路径的操作,如果没有就是默认的LocalDir</param>
        /// <returns></returns>
        public CommMsg DownloadFileToPath(string FileNameAndYearMonth, string SetPath = "")
        {
            try
            {
                //string FileName = FileNameAndYearMonth.Substring(FileNameAndYearMonth.IndexOf("/") + 1);
                string FileWebName = FileNameAndYearMonth.Replace("\\", "/").Replace("\\\\", "/");
                string SaveFileurl;
                if (string.IsNullOrWhiteSpace(SetPath))//如果是空就是默认路径
                {
                    SaveFileurl = LocalDir + FileNameAndYearMonth.Replace("/", "\\");
                }
                else
                {
                    SaveFileurl = SetPath;
                }

                FileInfo Finfo = new FileInfo(SaveFileurl);

                if (File.Exists(SaveFileurl))
                {
                    msg.Success = true;
                    msg.ErrMsg = "文件已存在!";
                    msg.ReturnStr = SaveFileurl;
                }
                else
                {
                    if (!Finfo.Directory.Exists)
                    {
                        Finfo.Directory.Create();
                    }
                    string GetFileurl = WebDirAll + FileWebName;
                    WebClient client = new WebClient();
                    client.Credentials = new NetworkCredential(WebUser, WebPw);
                    Uri FileWebUri = new Uri(GetFileurl);
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChangd);
                    client.DownloadDataCompleted +=  new DownloadDataCompletedEventHandler(DownloadFileCompleteZ);
                    if (FrmPreB == null)
                    {
                        FrmPreB = new FrmPressBar();

                    }
                    FrmPreB.Show();
                    FrmPreB.SetFileName = SaveFileurl;
                    client.DownloadFileAsync(FileWebUri, SaveFileurl);

                    //client.DownloadFile(GetFileurl, SaveFileurl);
                    msg.Success = true;
                    msg.ReturnStr = SaveFileurl;
                }
            }
            catch (Exception ex)
            {
                msg.Success = false;
                msg.ErrMsg = ex.Message;
            }
            return msg;
        }

 /// <summary>
        /// 下载页面
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        private void DownloadProgressChangd(object Sender, DownloadProgressChangedEventArgs e)
        {
            if (FrmPreB.IsHandleCreated)
            {
                FrmPreB.SetFilelengthValue = (int)e.TotalBytesToReceive;
                FrmPreB.SetFilelengthThisValue = (int)e.BytesReceived;
            }
        }
        /// <summary>
        /// 下载完成面
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        private void DownloadFileCompleteZ(object Sender, DownloadDataCompletedEventArgs e)
        {
            IsDownLoadSuc = true;
        }

单独需要from支持的情况下需要的数据:

 string WebDirAll = "";//全部路劲
    string LocalDir = Environment.CurrentDirectory + "\\WebTemp\\";
    string WebBaseDir = CommParameter.Url + "/" + CommParameter.DirName + "/";
    CommMsg msg = new CommMsg();
    string WebAdd = "";//ftp地址
    string WebUser = "";//ftp用户
    string WebPw = "";//ftp密码
    string WebDir = "";//ftp文件夹   

    /// <summary>
    /// 设置进度条最大位置
    /// </summary>
    private int _SetPressMaxValue;
    public int SetPressMaxValue
    {
        get
        {
            return _SetPressMaxValue;
        }
        set
        {
            _SetPressMaxValue = value; 
        }
    }
    /// <summary>
    /// 设置进度条最小位置
    /// </summary>
    private int _SetPressMinValue;
    public int SetPressMinValue
    {
        get
        {
            return _SetPressMinValue;
        }
        set
        {
            _SetPressMinValue = value;
            this.Invoke(new Action(() =>
            {
                this.ThisPressDown.Minimum = 0;
            }));
        }
    }
    /// <summary>
    ///  
    /// 设置文件大小 
    /// </summary>
    public int _SetFilelengthValue;
   
    public int SetFilelengthValue
    {

        get { return _SetFilelengthValue; }
        set
        {
            _SetPressMaxValue = value;
            _SetFilelengthValue = value;
            this.Invoke(new Action(() =>
            {
                this.ThisPressDown.Maximum = value;
            }));
        }
    }
    
    private int _SetFilelengthThisValue;
    /// <summary>
    /// 设置当前下载或者上传到达位置
    /// </summary>
    public int SetFilelengthThisValue
    {
        get
        {
            return _SetFilelengthThisValue;
        }
        set
        {
            _SetFilelengthThisValue = value;
            
            this.Invoke(new Action(() =>
            {
                ThisPressDown.Value = SetFilelengthThisValue;
                LBPressA.Text = $"当前进度:{SetFilelengthThisValue / 1024}K/{SetFilelengthValue / 1024}K";
            }));
        }
    }

   
    private string  _SetFileName;
    /// <summary>
    /// 设置当前文件名称
    /// </summary>
    public string SetFileName
    {
        get
        {
            return _SetFileName;
        }
        set
        {
            _SetFileName = value;
            this.Invoke(new Action(() =>
            {
                LBFilename.Text =value;
            }));
        }
    }

    /// <summary>
    /// 设置当前文件名称
    /// </summary>
    private string _SetPreeRemark;
    public string SetPreeRemark
    {
        get
        {
            return _SetPreeRemark;
        }
        set
        {
            _SetPreeRemark = value;
            this.Invoke(new Action(() =>
            {
                LBPressA.Text = $"当前进度:{SetFilelengthThisValue/1024}K/{SetFilelengthThisValue/1024}K" ;
            }));
        }
    }

    string FileNameAdd;
    public CommMsg OutMsg;

    public FrmUploadFile( string FileNameAddin)
    {
        InitializeComponent();
        FileNameAdd = FileNameAddin;
        WebAdd = CommParameter.Url;
        WebUser = CommParameter.UserName;
        WebPw = CommParameter.Pwd;
        WebDir = CommParameter.DirName;
        List<string> DirList = new List<string> { WebBaseDir, WebBaseDir + "Pic/", WebBaseDir + "File/", WebBaseDir + "Media/" };


        if (!Directory.Exists(LocalDir))
        {
            Directory.CreateDirectory(LocalDir);
        }
        if (string.IsNullOrEmpty(WebAdd) || string.IsNullOrEmpty(WebUser) || string.IsNullOrEmpty(WebPw))
        {
            throw new Exception("Ftp配置有问题,请在配置文件config下关于FTP所有的参数。");
        }
        else//获取全部路径
        {
            switch (CommParameter.SetType)
            {
                case FileType.图片:
                    WebDirAll = WebBaseDir + "Pic/";
                    break;
                case FileType.文档:
                    WebDirAll = WebBaseDir;
                    break;
                case FileType.音视频:
                    WebDirAll = WebBaseDir + "Media/";
                    break;
                default:
                    WebDirAll = WebBaseDir;
                    break;

            }
        }
        //OutMsg = UploadByBigFileweb(FileNameAdd);
        timer1.Start();
    }

调用方式:

FrmUploadFile frmUp = new FrmUploadFile(Openfile.FileName); 

show 或者 frmUp.ShowDialog()==OK都可以。为了界面可以展示开,定时2s开始下载或者上传数据。

另外其他的使用方法:

using (WebClient client = new WebClient())
            {
                string fileName = openFileDialog1.FileName;
                Uri url_upload = new Uri("change recive remote url");

                NameValueCollection nvc = new NameValueCollection();

                // data insert
                // nvc.Add("userid", "user01");
                // nvc.Add("workid", "work01");

                client.QueryString = nvc;
                client.UploadFileCompleted += (s, e1) =>
                {
                    string msg;

                    btn_Selectfile.Enabled = true;
                    btn_Upload.Enabled = true;

                    msg = Encoding.UTF8.GetString(e1.Result);

                    MessageBox.Show(msg);
                };
                client.UploadProgressChanged += (s, e1) =>
                {
                    double BytesSent = e1.BytesSent;
                    double TotalBytesToSend = e1.TotalBytesToSend;
                    int percent = (int)((BytesSent / TotalBytesToSend) * 100.0);

                    prog_Upload.Value = percent;
                    lbl_Percent.Text = percent + "%";

                };

                client.UploadFileAsync(url_upload, fileName);

                client.Dispose();
            }

FTP上传方法:

using (var request = new WebClient())
{
         request.Credentials = DefaultCredentials;
         try
         {
             request.UploadFileAsync(new Uri($"ftp://{ServerAddress}/{outfilepath}"), "STOR", infilepath);
             return true;
         }
         catch (WebException ex)
         {
             Logger.Write(ex.Message);
             return false;
         }
     }