在服务器A中我们可以编写如下代码:

<%@ Page Language="C#" EnableSessionState="ReadOnly" Async="true" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Net" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <mce:script type="text/C#" runat="server"><!-- BinaryReader ms; UploadInfo uploadInfo = null; protected void Page_Load(object sender, EventArgs args) { if (this.IsPostBack) { uploadInfo = this.Session["UploadInfo"] as UploadInfo; if (uploadInfo == null) { // 让父页面知道无法处理上传 const string js = "window.parent.onComplete('error', '无法上传文件。请刷新页面,然后再试一次);"; ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), "progress", js, true); } else { // 让服务端知道我们还没有准备好.. uploadInfo.IsReady = false; try { // 读取要上传的文件 FileStream fs = new FileStream(this.fileUpload.PostedFile.FileName, FileMode.Open, FileAccess.Read); ms = new BinaryReader(fs); string newFile = DateTime.Now.Ticks.ToString(); string exit = this.fileUpload.FileName.Substring(this.fileUpload.FileName.IndexOf('.')); newFile = newFile + exit; UriBuilder url = new UriBuilder("http://192.168.25.27:8056/UploadFileHander.ashx");//上传路径 url.Query = string.Format("filename={0}", newFile);//上传url参数 uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength; uploadInfo.FileName = newFile; uploadInfo.UploadedLength = 0; //文件存在 初始化... uploadInfo.IsReady = true; WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);//委托异步上传事件 wc.OpenWriteAsync(url.Uri);//开始异步上传 const string js = "window.parent.onComplete('success', '{0} 已成功上传,重命名为:{1}:文件大小:{2}');"; ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), "progress", string.Format(js, Path.GetFileName(this.fileUpload.FileName), DateTime.Now.ToString("yyyy-MM") + "/" + DateTime.Now.Day + "/" + newFile, uploadInfo.ContentLength), true); } catch (Exception ex) { Response.Write(ex.Message); } } } } protected void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) { int bufSize = 10; int byteGet = 0; byte[] buf = new byte[bufSize]; while ((byteGet = ms.Read(buf, 0, bufSize)) > 0)//循环读取,上传 { e.Result.Write(buf, 0, byteGet);//注意这里 uploadInfo.UploadedLength += byteGet; } // 让父页面知道已经处理上传完毕 e.Result.Close();//关闭 ms.Close(); } // --></mce:script> <mce:style type="text/css"><!-- BODY{margin:0; padding:0; background-color:#F0F8FF;} --></mce:style><style type="text/css" mce_bogus="1"> BODY{margin:0; padding:0; background-color:#F0F8FF;} </style> </head> <body> <form id="form" runat="server" enctype="multipart/form-data"> <asp:ScriptManager ID="scriptManager" runat="server" /> <mce:script type="text/javascript"><!-- function pageLoad(sender, args){ window.parent.register( $get('<%= this.form.ClientID %>'), $get('<%= this.fileUpload.ClientID %>') ); } // --></mce:script> <div> <asp:FileUpload ID="fileUpload" runat="server" Width="100%" /> </div> </form> </body> </html>

在服务器B中我们创建一个接受文件。UploadFileHander.ashx 来负责文件的接受和保存:

using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.IO; namespace WebApplication1 { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class UploadFileHander : IHttpHandler { public void ProcessRequest(HttpContext context) { try { string dateNow = DateTime.Now.ToString("yyyy-MM"); // 设置路径 string path = "D://ks5u/NewSystem/" + dateNow + "/" + DateTime.Now.Day; if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } string newFile = Path.GetFileName(context.Request.QueryString["filename"]); //文件存在 初始化... long UploadedLength = 0; //缓存 int bufferSize = 1; byte[] buffer = new byte[bufferSize]; // 保存字节 using (FileStream fs = new FileStream(Path.Combine(path, newFile), FileMode.Create)) { while (UploadedLength < context.Request.InputStream.Length) { //从输入流放进缓冲区 int bytes = context.Request.InputStream.Read(buffer, 0, bufferSize); // 字节写入文件流 fs.Write(buffer, 0, bytes); // 更新大小 UploadedLength += bytes; // 线程睡眠 上传就更慢 这样就可以看到进度条了 } } }catch (Exception e) { context.Response.ContentType = "text/plain"; context.Response.Write("上传失败, 错误信息:" + e.Message); } } public bool IsReusable { get { return false; } } } }

asp.net 如何用webclient上传文件相关推荐

  1. WebClient上传文件至服务器和下载服务器文件至客户端

    #region WebClient上传文件至服务器 /// <summary> /// WebClient上传文件至服务器 /// </summary> /// <par ...

  2. 如何用git上传文件

    首先先初始化,找到你想要上传到git的文件夹 然后git init 然后将所有文件提交 git add * 用git commit -m 'ss',没有邮箱和名字会叫你设置 设置完成然后在重新git ...

  3. WebClient 上传文件

    MVC下 服务端代码: [HttpPost]public ActionResult UploadImg(string types){string data = "";try{if ...

  4. asp上传文件到ftp服务器,ASP.NET 中使用 FTP 上传文件

    public static void Upload(string filePath) { FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(&q ...

  5. linux如何用rz上传文件,Linux使用rz命令上传文件

    Persistent Data Structures 原文链接:http://www.codeproject.com/Articles/9680/Persistent-Data-Structures ...

  6. 解决asp.net中使用FckEditor上传文件,中文名称乱码的问题

    其实很Easy,需要在config中尽心设置: <globalization requestEncoding="UTF-8" responseEncoding="U ...

  7. jsch 移动服务器上文件,jsch上传文件到服务器

    需求就是上传文件到服务器,服务器的存储地址由程序决定然后可以自动创建. 使用第三方:jsch JSch 是SSH2的一个纯Java实现.它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文 ...

  8. C 上传文件到服务器(含接收端源码)

    2019独角兽企业重金招聘Python工程师标准>>> 本文demo下载地址:http://www.wisdomdd.cn/Wisdom/resource/articleDetail ...

  9. C# winform 上传文件 (多种方案)

    方案一: 注意:要开启虚拟目录的"写入"权限,要不然就报 403 错误 工作中用到winform上传文件(-_-!,很少用winform,搞了半天) 碰到一点问题,解决如下 1.5 ...

最新文章

  1. RecyclerView 显示不全的问题.
  2. Linux 混合编译opencv与opencv_contrib的android版本
  3. python提高运行效率_提高CPU密集型任务执行效率——Python多进程介绍,内附实例代码...
  4. Oracle客户端配置
  5. fatal error C1010: 在查找预编译头时遇到意外的文件结尾
  6. Hyperledger fabric并发并行性
  7. html网页显示时中文乱码
  8. UWP 手绘视频创作工具技术分享系列
  9. arcmap中图斑面积代表_arcmap计算面积_ArcMap怎么重计算图斑面积?arcmap使用手册_arcmap计算面积...
  10. 面向对象-封装继承多态
  11. 微波雷达传感器模块,智能感知人体存在,实时感应交互控制应用
  12. Ubuntu 设置桥接网络
  13. Mac系统重置快捷键
  14. 【PIL处理图片】小技巧之画虚线、加粗字体、长文本自动分行(符号处理)
  15. 消防审批时限减了一半
  16. win10卸载更新的方法
  17. C/C++编程分享:C++ 实现太阳系行星项目系统
  18. 免安装版(解压缩版)MySQL安装
  19. STC89C52单片机
  20. 关于dateadd与datediff的使用方法

热门文章

  1. 计算机控制菜单,CRH1型动车组计算机控制系统IDU菜单系统功能概述.docx
  2. VSCode报错:Import “numpy“ could not be resolved Pylance
  3. Qt QString使用
  4. 2023实验室装修设计十大要点,附注意事项和流程
  5. x86 --- 任务隔离特权级保护
  6. 父母都该为孩子安全做的75件事
  7. VS Code插件之 Markdown 篇
  8. 树形结构(1)(Java语言)——树的基本概念
  9. Redis很牛逼很秀!轻松实现实时订阅推送
  10. Nowcoder专项练习:网络基础(一)