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. 关于Android悬浮窗要获取按键响应的问题

    要在Android中实现顶层的窗口弹出,一般都会用WindowsManager来实现,但是几乎所有的网站资源都是说弹出的悬浮窗不用接受任何按键响应. 而问题就是,我们有时候需要他响应按键,比如电视上的 ...

  2. .NET 托管堆和垃圾回收

       托管堆基础 简述:每个程序都要使用这样或那样的资源,包括文件.内存缓冲区.屏幕空间.网络连接.....事实上,在面向对象的环境中,每个类型都代表可供程序使用的一种资源.要使用这些资源,必须为代表 ...

  3. SQL Server 中的事务和锁(三)-Range S-U,X-X 以及死锁

    在上一篇中忘记了一个细节.Range T-K 到底代表了什么?Range T-K Lock 代表了在 SERIALIZABLE 隔离级别中,为了保护范围内的数据不被并发的事务影响而使用的一类锁模式(避 ...

  4. 经典的iptables shell脚本

    PS:这个iptables脚本不错,很实用,根据实际应用改一下就可以自己用.分享出来,供大家来参考.原作者佚名.源代码如下: #!/bin/sh modprobe ipt_MASQUERADE mod ...

  5. C#中常用的排序算法的时间复杂度和空间复杂度

    常用的排序算法的时间复杂度和空间复杂度   常用的排序算法的时间复杂度和空间复杂度 排序法 最差时间分析 平均时间复杂度 稳定度 空间复杂度 冒泡排序 O(n2) O(n2) 稳定 O(1) 快速排序 ...

  6. mina 粘包、多包和少包的解决方法

    转载自:http://freemart.iteye.com/blog/836654 使用过 mina 的同学应该都遇到到过,在解码时少包.多包的问题,查阅了很多资料还是迷迷糊糊的,经过不懈努力,终于解 ...

  7. Oracle基础 shutdown和startup

    一.shutdown命令:SHUTDOWN有四个参数:NORMAL.TRANSACTIONAL.IMMEDIATE.ABORT.缺省不带任何参数时表示是NORMAL. SHUTDOWN NORMAL: ...

  8. React Native(ios)项目中logo,启动屏设置

    由于logo和启动屏尺寸多,react native(ios)中没有命令可以自动生成各种的尺寸,所以可以使用以下办法:在ionic项目中生成(使用命令:ionic resources)后,再粘贴到re ...

  9. DNS的递归查询和迭代查询

    百度运维部二面,直接懵逼的节奏 (1)递归查询 递归查询是一种DNS 服务器的查询模式,在该模式下DNS 服务器接收到客户机请求, 必须使用一个准确的查询结果回复客户机. 如果DNS 服务器本地没有存 ...

  10. 转: Android基于HLS和RTMP协议的第三方SDK选择

    转自: http://isunxu.xyz/android/between-rtmp-and-hls-third-party-choice/ 协议的详解网上资料都太多了,我就不赘述了.Android上 ...