silverlight webclient实现上传、下载、删除、读取文件
1.上传
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{ //弹出打开文件对话框要求用户自己选择在本地端打开的图片文件
Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
Multiselect = false //不允许多选
}; if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
{
//fileinfo = openFileDialog.Files; //取得所选择的文件,其中Name为文件名字段,作为绑定字段显示在前端
FileInfo fileinfo = openFileDialog.File; if (fileinfo != null)
{
WebClient webclient = new WebClient(); string uploadFileName = fileinfo.Name.ToString(); //获取所选文件的名字 #region 把文件上传到服务器上 Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上传处理程序 webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
webclient.Headers["Content-Type"] = "multipart/form-data";//"application/x-www-form-urlencoded";// webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); #endregion }
else
{
MessageBox.Show("请选取想要上载的图片!!!");
}
} }
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{ //将图片数据流发送到服务器上 // e.UserState - 需要上传的流(客户端流)
Stream clientStream = e.UserState as Stream;
// e.Result - 目标地址的流(服务端流)
Stream serverStream = e.Result;
byte[] buffer = new byte[clientStream.Length];
int readcount = ;
// clientStream.Read - 将需要上传的流读取到指定的字节数组中
while ((readcount = clientStream.Read(buffer, , buffer.Length)) > )
{
// serverStream.Write - 将指定的字节数组写入到目标地址的流
serverStream.Write(buffer, , readcount);
}
serverStream.Close();
clientStream.Close();
}
void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
{
//判断写入是否有异常
if (e.Error != null)
{
System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString());
}
else
{
System.Windows.Browser.HtmlPage.Window.Alert("文件上传成功!!!");
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web; namespace SilverlightApplication9.Web
{
/// <summary>
/// WebClientUpLoadStreamHandler 的摘要说明
/// </summary>
public class WebClientUpLoadStreamHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
//获取上传的数据流
string fileNameStr = context.Request.QueryString["fileName"]; Stream sr = context.Request.InputStream;
try
{
string filename = ""; filename = fileNameStr; byte[] buffer = new byte[];
int bytesRead = ;
//将当前数据流写入服务器端文件夹ClientBin下
string targetPath = context.Server.MapPath("Pics/" + filename); using (FileStream fs = File.Create(targetPath, ))
{
while ((bytesRead = sr.Read(buffer, , buffer.Length)) > )
{
//向文件中写信息
fs.Write(buffer, , bytesRead);
}
} context.Response.ContentType = "text/plain";
context.Response.Write("上传成功");
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败, 错误信息:" + e.Message);
}
finally
{ sr.Dispose(); } } public bool IsReusable
{
get
{
return false;
}
}
}
}
2.下载
2.1下载方法1
#region 下载图片
SaveFileDialog sfd = null;
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
//向指定的Url发送下载流数据请求
string imgUrl = "http://localhost:51896/Pics/Wildlife.wmv";
Uri endpoint = new Uri(imgUrl);
sfd = new SaveFileDialog()
{
DefaultExt = "jpeg",
Filter = "Text files (*.jpeg)|*.jpeg|All files (*.*)|*.*",
FilterIndex =
}; if (sfd.ShowDialog() == true)
{ Uri end1point = new Uri(imgUrl);
WebClient client = new WebClient();
client.OpenReadCompleted += (ss, ee) =>
{
Stream pngStream = ee.Result;
byte[] binaryData = new Byte[pngStream.Length];
pngStream.Read(binaryData, , (int)pngStream.Length);
Stream stream = sfd.OpenFile();
stream.Write(binaryData, , binaryData.Length);
stream.Close(); };
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
client.OpenReadAsync(endpoint);
} } void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//DownloadProgressChangedEventArgs.ProgressPercentage - 下载完成的百分比
//DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
//DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
//DownloadProgressChangedEventArgs.UserState - 用户标识 this.tbMsgString.Text = string.Format("完成百分比:{0} 当前收到的字节数:{1} 资料大小:{2} ",
e.ProgressPercentage.ToString() + "%",
e.BytesReceived.ToString(),
e.TotalBytesToReceive.ToString()); } #endregion
2.2下载方法2
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Window.Eval("window.location.href='http://localhost:51896/download.ashx?filename=IMG_20140329_093302.jpg';");
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace SilverlightApplication9.Web
{
/// <summary>
/// download 的摘要说明
/// </summary>
public class download : IHttpHandler
{
private long ChunkSize = ;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
public void ProcessRequest(HttpContext context)
{
//string fileName = "123.jpg";//客户端保存的文件名
String fileName = context.Request.QueryString["filename"];
string filePath = context.Server.MapPath(@"Pics/IMG_20140329_093302.jpg");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true)
{
byte[] buffer = new byte[ChunkSize];
context.Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length;//获得下载文件的总大小
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
while (dataLengthToRead > && context.Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, , Convert.ToInt32(ChunkSize));//读取的大小
context.Response.OutputStream.Write(buffer, , lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
context.Response.Close();
context.Response.End();
}
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
} public bool IsReusable
{
get
{
return false;
}
}
}
}
3.删除
private void WebClientCommand(string isDeleteParam, int sort)
{
string uploadFileName = null;
WebClient webclient = new WebClient();
Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}&result={1}", uploadFileName, isDeleteParam), UriKind.Absolute);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
webclient.UploadStringAsync(upTargetUri,""); }
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error == null)
{
EasySL.Controls.Window.Alert("删除成功", this.floatePanel);
}
}
using Huitu.Bjsq.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web; namespace EasySL.Web
{
/// <summary>
/// WebClientUpLoadStreamHandler 的摘要说明
/// </summary>
public class WebClientUpLoadStreamHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//获取上传的数据流
string fileNameStr = context.Request.QueryString["fileName"];
string paramResult = context.Request.QueryString["result"];
Stream sr = context.Request.InputStream;
try
{
string filename = "";
filename = fileNameStr;
byte[] buffer = new byte[];
int bytesRead = ;
if (!string.IsNullOrEmpty(paramResult))
{
foreach (string item in paramResult.Split('|'))
{
string paramDel = context.Server.MapPath("FileLoad/" + item);
if (File.Exists(paramDel))
{
File.Delete(paramDel);
context.Response.ContentType = "text/plain";
context.Response.Write("删除成功");
}
}
}
else
{
//将当前数据流写入服务器端文件夹ClientBin下
string targetPath = context.Server.MapPath("FileLoad/" + filename);
using (FileStream fs = File.Create(targetPath, ))
{
while ((bytesRead = sr.Read(buffer, , buffer.Length)) > )
{
//向文件中写信息
fs.Write(buffer, , bytesRead);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("上传成功");
}
} catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败, 错误信息:" + e.Message);
}
finally
{ sr.Dispose(); }
} public bool IsReusable
{
get
{
return false;
}
}
}
}
4.对于处理上传大文件的处理
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="" executionTimeout="" />
</system.web>
</configuration>
5.将程序发布在iis上注意的问题(代码是VS服务器运行正常,但是发布到IIS后上传文件总是失败。后来发现,我发布到IIS的虚拟目录,所以路径变了。)
Uri uri = new Uri(string.Format("/DataHandler.ashx?filename={0}", fileName), UriKind.Relative);
// Uri uri = new Uri("http://localhost/SEManage/UploadImg.ashx", UriKind.Absolute);
WebClient client = new WebClient();
将Uri中的绝对路径,修改为相对路径
6.读取文件操作(.txt)
private void SetWeather()
{
WebClient downReader = new WebClient();
downReader.Encoding = System.Text.Encoding.UTF8;
downReader.OpenReadCompleted += (s, e) =>
{
if (e.Error == null)
{
using (StreamReader reader = new StreamReader(e.Result))
{
string[] line = reader.ReadToEnd().Split('|');
}
}
}
downReader.OpenReadAsync(new Uri("../AppConfig/Weather.txt", UriKind.Relative));
}
private void WeatherDispatcherTimer()
{
//创建计时器
System.Windows.Threading.DispatcherTimer myWeatherTimer = new System.Windows.Threading.DispatcherTimer();
//创建间隔时间
myWeatherTimer.Interval = new TimeSpan(, , , );
//创建到达间隔时间后需执行的函数
myWeatherTimer.Tick += (ss, ee) =>
{
InitDataWeather();
};
myWeatherTimer.Start();
}
silverlight webclient实现上传、下载、删除、读取文件的更多相关文章
- Python 一键上传下载&一键提交文件到SVN入基线工具
一键上传下载&一键提交文件到SVN入基线工具 by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用说明 1 注: 根据我司项目规则订制的一套工具,集成以下功能,源码 ...
- Android连接socket服务器上传下载多个文件
android连接socket服务器上传下载多个文件1.socket服务端SocketServer.java public class SocketServer { ;// 端口号,必须与客户端一致 ...
- 使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器
前言 为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下. 本 ...
- 使用C#WebClient类访问(上传/下载/删除/列出文件目录)
在使用WebClient类之前,必须先引用System.Net命名空间,文件下载.上传与删除的都是使用异步编程,也可以使用同步编程, 这里以异步编程为例: 1)文件下载: static void Ma ...
- Struts2 文件上传,下载,删除
本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用Fi ...
- java 通过sftp服务器上传下载删除文件
最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...
- SpringMVC ajax技术无刷新文件上传下载删除示例
参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...
- java FTP 上传下载删除文件
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
- 用jsch.jar实现SFTP上传下载删除
java类: 需要引用的jar: jsch-0.1.53.jar 关于jsch有篇文章关于目录的问题写得非常好:http://www.zzzyk.com/show/9f02969327434a6c.h ...
随机推荐
- 计算运行时间工具timeit
Table of Contents 1. timeit的功能和用法 2. 其它 3. 参考资料 timeit的功能和用法 timeit 模块提供了测试一小段代码运行时间的功能.我前面有一篇文章用它来测 ...
- kafka删除topic
手动: 删除kafka存储目录(server.properties文件log.dirs配置,默认为"/tmp/kafka-logs")相关topic目录 删除zookeeper & ...
- C# 程序集反射
namespace AssemblyLibrary { public class AssemblyLibrary { public static object LoadAssembly(string ...
- [原创] Web UI自动化应用测试框架实践 - 概览
之前为我们部门做的一个UI框架.不能纯粹解读为框架,主要是做了一些简单的分层设计,以解决稳定性.降低复杂性.提升可维护性以及快速构建测试用例等实际问题. 主要部分:1. 测试数据.主要提供测试类库需要 ...
- CSS3笔记
CSS/CSS3在线手册:http://www.css119.com/book/css/ CSS3实现水平垂直居中:http://bbs.html5cn.org/thread-87300-1-1. ...
- phpQuery用法
了解phpQuery使用前了温习jquery.js的选择用法 jquery选择器,还有一个衍生产品QueryList 例: include 'phpQuery.php'; phpQuery::newD ...
- Part 18 Indexes in sql server
Indexes in sql server Clustered and nonclustered indexes in sql server Unique and Non Unique Indexes ...
- Hadoop YARN配置参数剖析—RM与NM相关参数
注意,配置这些参数前,应充分理解这几个参数的含义,以防止误配给集群带来的隐患.另外,这些参数均需要在yarn-site.xml中配置. 1. ResourceManager相关配置参数 (1) ...
- .NET XML文件增删改查
查询 采用的是DataSet 的 ReadXML方法. DataSet ds = new System.Data.DataSet(); ds.ReadXml("bdc.xml"); ...
- Cocos2d-JS坐标系
在图形图像和游戏应用开发中坐标系是非常重要的,我们在Android和iOS等平台应用开发的时候使用的二维坐标系它的原点是在左上角的.而在Cocos2d-JS坐标系中它原点是在左下角的,而且Cocos2 ...