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 ...
随机推荐
- [golang学习] 在idea中code & debug
[已废弃]不需要看 idea 虽然审美倒退了n年. 不过功能还是相当好用的. idea 的go插件堪称最好的go ide. 1. 语法高亮支持 2. 智能提示 3. 跳转定义(反跳转回来) 4. 集成 ...
- c++ 设计模式9 (Abstract Factory 抽象工厂模式)
5.2 抽象工厂模式 动机:在软件系统中,经常面临着“一系列相互依赖的对象”的创建工作:同时,由于需求的变化,往往存在更多系列对象的创建工作. 代码示例: 实现利用数据库的业务逻辑,支持多数据库(Sq ...
- struts2与cookie实现自动登录和验证码验证
主要介绍struts2与cookie结合实现自动登录 struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取 struts2的jar包 链接数据库文件 db.pr ...
- 1.5.4 什么是Filter--过滤器
什么是Filter--过滤器 像分词器(tokenizer)一样,过滤器(filter)消耗输入,产生token流.过滤器同样从org.apache.lucene.analysis.TokenStre ...
- Android开发 SDK NDK下载
2014.7版本 ADT Bundle http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.ziphttp://dl.go ...
- 索引与优化like查询
1. like %keyword 索引失效,使用全表扫描.但可以通过翻转函数+like前模糊查询+建立翻转函数索引=走翻转函数索引,不走全表扫描. 2. like keyword% 索引有 ...
- codeforces 590C C. Three States(bfs+连通块之间的最短距离)
题目链接: C. Three States time limit per test 5 seconds memory limit per test 512 megabytes input standa ...
- 转: 透过CAT,来看分布式实时监控系统的设计与实现
评注: 开源的分布式监控系统 转:http://www.infoq.com/cn/articles/distributed-real-time-monitoring-and-control-syste ...
- 【转】华为Java编程军规,每季度代码验收标准
引言: 这个标准是衡量代码本身的缺陷,也是衡量一个研发人员本身的价值. 军规一:[避免在程序中使用魔鬼数字,必须用有意义的常量来标识.] 军规二:[明确方法的功能,一个方法仅完成一个功能.] 军规三: ...
- Wonderful Sentense
1.Sorry if I might sound arrogant or offensive. 2.Any further question? 3.How dare you! 4.Try it if ...