Silverlight从客户端上传文件到服务器
这里介绍的是一种利用WebClient手动发送Stream到服务器页面的上传文件方法。
一、服务器接收文件
这里使用一个ASHX页面来接收和保存Silverlight传来的Stream,页面代码如下:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Silverlight { /// <summary> /// FileUploadHandler 的摘要说明 /// </summary> public class FileUploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { //获取上传参数 - 文件名 string fileName = context.Request["FileName"]; //获取上传的数据流 using (Stream inputStream = context.Request.InputStream) { try { //数据缓冲区 byte[] buffer = new byte[4096]; int bytesRead = 0; //准备保存路径和文件名 string filePath = string.Format(@"D:\FileUpload\"); //检查保存路径是否存在 if (!Directory.Exists(filePath)) { //不存在进行创建 Directory.CreateDirectory(filePath); } //准备写入文件流 using (FileStream fs = File.Create(filePath + fileName, 4096)) { //开始循环写入文件 while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //向文件中写信息 fs.Write(buffer, 0, bytesRead); } } //上传成功 context.Response.ContentType = "text/plain"; context.Response.Write("上传成功"); } catch (Exception e) { //上传出错 context.Response.ContentType = "text/plain"; context.Response.Write("上传失败, 错误信息:" + e.Message); } } } public bool IsReusable { get { return false; } } } }
这里保存文件的主要流程就是接收上传参数,准备保存文件,通过读取上传流保存文件内容。
二、客户端发送文件
客户端发送文件使用的是WebClient类。
首先建立一个WebClient连接:
//准备上传连接 WebClient uploadClient = new WebClient(); uploadClient.Headers["Content-Type"] = "multipart/form-data"; //连接打开后的操作 uploadClient.OpenWriteCompleted += uploadClient_OpenWriteCompleted; //流写入完成后的操作 uploadClient.WriteStreamClosed += uploadClient_WriteStreamClosed; //打开上传连接 uploadClient.OpenWriteAsync(new Uri("", UriKind.Relative), "POST", fileStream);
WebClient打开连接后的处理:
void uploadClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) { //将文件数据流发送到服务器上 // e.UserState - 需要上传的流(客户端流) using (Stream clientStream = e.UserState as Stream) { // e.Result - 目标地址的流(服务端流) using (Stream serverStream = e.Result) { byte[] buffer = new byte[4096]; int readcount = 0; // clientStream.Read - 将需要上传的流读取到指定的字节数组中 while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0) { // serverStream.Write - 将指定的字节数组写入到目标地址的流 serverStream.Write(buffer, 0, readcount); } } } }
WebClient连接关闭后的处理:
void uploadClient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e) { //判断写入是否有异常 if (e.Error != null) { MessageBox.Show("上传失败!", e.Error.Message.ToString()); } else { MessageBox.Show("上传成功!", "文件已保存!"); } }
客户端这边主要就是打开连接,然后打开服务器的接收流,然后传输文件数据流到服务器。
输了你,赢了世界又如何...
分类:
ASP.NET
, Silverlight
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!