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实现上传、下载、删除、读取文件的更多相关文章

  1. Python 一键上传下载&一键提交文件到SVN入基线工具

    一键上传下载&一键提交文件到SVN入基线工具   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用说明 1   注: 根据我司项目规则订制的一套工具,集成以下功能,源码 ...

  2. Android连接socket服务器上传下载多个文件

    android连接socket服务器上传下载多个文件1.socket服务端SocketServer.java public class SocketServer { ;// 端口号,必须与客户端一致 ...

  3. 使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器

    前言 为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下. 本 ...

  4. 使用C#WebClient类访问(上传/下载/删除/列出文件目录)

    在使用WebClient类之前,必须先引用System.Net命名空间,文件下载.上传与删除的都是使用异步编程,也可以使用同步编程, 这里以异步编程为例: 1)文件下载: static void Ma ...

  5. Struts2 文件上传,下载,删除

    本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用Fi ...

  6. java 通过sftp服务器上传下载删除文件

    最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...

  7. SpringMVC ajax技术无刷新文件上传下载删除示例

    参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...

  8. java FTP 上传下载删除文件

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  9. 用jsch.jar实现SFTP上传下载删除

    java类: 需要引用的jar: jsch-0.1.53.jar 关于jsch有篇文章关于目录的问题写得非常好:http://www.zzzyk.com/show/9f02969327434a6c.h ...

随机推荐

  1. iOS H5容器的一些探究(二):iOS 下的黑魔法 NSURLProtocol

    来源:景铭巴巴 链接:http://www.jianshu.com/p/03ddcfe5ebd7 iOS H5 容器的一些探究(一):UIWebView 和 WKWebView 的比较和选择 一.前言 ...

  2. IIS 之 HTTP 错误 403.14 - Forbidden

    错误如下图所示: 其实,这个提示下面已经交代了怎么解决问题,现在告诉大家具体的详细步骤. 方法一:配置" 默认文档 " 方法二:启用" 目录浏览 "

  3. [Java] HashMap遍历的两种方式

    Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml第一种: Map map = new HashMap( ...

  4. 【阿里云产品公测】阿里云ECS服务器,PTS网站性能

    作者:阿里云用户321房产网 系统环境:CentOS 6.3 运行组件:Nginx + php + mysql + 缓存加速为eAccelerator 运行网站:基于phpcms开发模板:321房产网 ...

  5. 源自梦想 自定义ViewGroup的整理_1

    今天说说自定义控件,稍微偏底层一点的东西.今天的主要任务是自己完全写代码,写一个ViewGroup,实现一个类似ViewPager这样的一个功能. 大家自定义View肯定写过,不过估计写的也不多.等大 ...

  6. iOS 多线程讲解2

    1.GCD其他方法 1.GCD应用 单例模式 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@&qu ...

  7. Android-Activity生命周期从onStart直接到onStop

    一般应用场景中,onStart执行后都是要执行onResume,但是如果在onStart中调用了finish,会直接执行onStop.

  8. JAX-WS开发WebService程序

    近来公司里要用的到WebService做开发,所以就自己学习了一下,刚开始感觉挺难的,但是真正学会以后,原来这么简单. 今天把这些东西哦记下来,以便日后的复习. 我来介绍一下我的开发环境:Eclips ...

  9. Python一些难以察觉的错误

    Python一些难以察觉的错误 今天把微博的收藏夹打开,发现以前很多收藏的好文章还没有细细研究,今天开始要慢慢研究总结总结.今天看的这篇文章地址: http://blog.amir.rachum.co ...

  10. 剑指Offer16 判断子树

    /************************************************************************* > File Name: 17_Mirror ...