当前位置: 首页 > news >正文

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

使用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);//必须加入条件PUTif (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;}}

相关文章:

  • FortiGate SSL VPN host check添加自定义防病毒软件
  • VS开发 - 静态编译和动态编译的基础实践与混用
  • Python爬虫bs4的基本使用
  • mfc140u.dll缺失?快速解决方法全解析,解决mfc140u.dll错误
  • Harmony商城项目
  • SpringBoot日常:链路追踪skyworking的接入
  • MYSQL求月份同比数据和环比数据
  • 【步联科技身份证】 身份证读取与解析———未来之窗行业应用跨平台架构
  • 深度学习应用详解
  • 叶国富“推翻”马云新零售,零售新王此刻登基?
  • 线性基学习DAY2
  • 【libp2p——NAT】
  • ansible学习之 Facts
  • 平安养老险肇庆中心支公司开展“2024年金融教育宣传月”活动
  • matlab-批处理图像质量变化并形成折线图 (PSNR)
  • .pyc 想到的一些问题
  • 77. Combinations
  • iOS | NSProxy
  • iOS 系统授权开发
  • Java的Interrupt与线程中断
  • Linux快速配置 VIM 实现语法高亮 补全 缩进等功能
  • Lsb图片隐写
  • PaddlePaddle-GitHub的正确打开姿势
  • Python利用正则抓取网页内容保存到本地
  • Redis 中的布隆过滤器
  • Transformer-XL: Unleashing the Potential of Attention Models
  • Vue--数据传输
  • 编写高质量JavaScript代码之并发
  • 湖南卫视:中国白领因网络偷菜成当代最寂寞的人?
  • 类orAPI - 收藏集 - 掘金
  • 前端技术周刊 2019-01-14:客户端存储
  • 使用Tinker来调试Laravel应用程序的数据以及使用Tinker一些总结
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 微信开源mars源码分析1—上层samples分析
  • 想晋级高级工程师只知道表面是不够的!Git内部原理介绍
  • ​ArcGIS Pro 如何批量删除字段
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • ​学习一下,什么是预包装食品?​
  • # Python csv、xlsx、json、二进制(MP3) 文件读写基本使用
  • #我与Java虚拟机的故事#连载03:面试过的百度,滴滴,快手都问了这些问题
  • #我与Java虚拟机的故事#连载04:一本让自己没面子的书
  • ${ }的特别功能
  • (4.10~4.16)
  • (el-Transfer)操作(不使用 ts):Element-plus 中 Select 组件动态设置 options 值需求的解决过程
  • (Python第六天)文件处理
  • (zt)基于Facebook和Flash平台的应用架构解析
  • (二)JAVA使用POI操作excel
  • (二)斐波那契Fabonacci函数
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (附源码)c#+winform实现远程开机(广域网可用)
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (七)理解angular中的module和injector,即依赖注入
  • (切换多语言)vantUI+vue-i18n进行国际化配置及新增没有的语言包
  • (三)elasticsearch 源码之启动流程分析