silverlight webclient实现上传、下载、删除操作

1.上传

 1  private void Button_Click_1(object sender, RoutedEventArgs e)
2 {
3 OpenFileDialog openFileDialog = new OpenFileDialog()
4 { //弹出打开文件对话框要求用户自己选择在本地端打开的图片文件
5 Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
6 Multiselect = false //不允许多选
7 };
8
9 if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
10 {
11 //fileinfo = openFileDialog.Files; //取得所选择的文件,其中Name为文件名字段,作为绑定字段显示在前端
12 FileInfo fileinfo = openFileDialog.File;
13
14 if (fileinfo != null)
15 {
16 WebClient webclient = new WebClient();
17
18 string uploadFileName = fileinfo.Name.ToString(); //获取所选文件的名字
19
20 #region 把文件上传到服务器上
21
22 Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上传处理程序
23
24 webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
25 webclient.Headers["Content-Type"] = "multipart/form-data";//"application/x-www-form-urlencoded";//
26
27 webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
28 webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);
29
30 #endregion
31
32 }
33 else
34 {
35 MessageBox.Show("请选取想要上载的图片!!!");
36 }
37 }
38
39 }
40 void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
41 {
42
43 //将图片数据流发送到服务器上
44
45 // e.UserState - 需要上传的流(客户端流)
46 Stream clientStream = e.UserState as Stream;
47 // e.Result - 目标地址的流(服务端流)
48 Stream serverStream = e.Result;
49 byte[] buffer = new byte[clientStream.Length];
50 int readcount = 0;
51 // clientStream.Read - 将需要上传的流读取到指定的字节数组中
52 while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0)
53 {
54 // serverStream.Write - 将指定的字节数组写入到目标地址的流
55 serverStream.Write(buffer, 0, readcount);
56 }
57 serverStream.Close();
58 clientStream.Close();
59 }
60 void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
61 {
62 //判断写入是否有异常
63 if (e.Error != null)
64 {
65 System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString());
66 }
67 else
68 {
69 System.Windows.Browser.HtmlPage.Window.Alert("文件上传成功!!!");
70 }
71 }

 1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Web;
6
7 namespace SilverlightApplication9.Web
8 {
9 /// <summary>
10 /// WebClientUpLoadStreamHandler 的摘要说明
11 /// </summary>
12 public class WebClientUpLoadStreamHandler : IHttpHandler
13 {
14
15 public void ProcessRequest(HttpContext context)
16 {
17 //获取上传的数据流
18 string fileNameStr = context.Request.QueryString["fileName"];
19
20 Stream sr = context.Request.InputStream;
21 try
22 {
23 string filename = "";
24
25 filename = fileNameStr;
26
27 byte[] buffer = new byte[4096];
28 int bytesRead = 0;
29 //将当前数据流写入服务器端文件夹ClientBin下
30 string targetPath = context.Server.MapPath("Pics/" + filename);
31
32 using (FileStream fs = File.Create(targetPath, 4096))
33 {
34 while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
35 {
36 //向文件中写信息
37 fs.Write(buffer, 0, bytesRead);
38 }
39 }
40
41 context.Response.ContentType = "text/plain";
42 context.Response.Write("上传成功");
43 }
44 catch (Exception e)
45 {
46 context.Response.ContentType = "text/plain";
47 context.Response.Write("上传失败, 错误信息:" + e.Message);
48 }
49 finally
50 { sr.Dispose(); }
51
52 }
53
54 public bool IsReusable
55 {
56 get
57 {
58 return false;
59 }
60 }
61 }
62 }

2.下载
2.1下载方法1

 1  #region  下载图片
2 SaveFileDialog sfd = null;
3 private void btnDownload_Click(object sender, RoutedEventArgs e)
4 {
5 //向指定的Url发送下载流数据请求
6 string imgUrl = "http://localhost:51896/Pics/Wildlife.wmv";
7 Uri endpoint = new Uri(imgUrl);
8 sfd = new SaveFileDialog()
9 {
10 DefaultExt = "jpeg",
11 Filter = "Text files (*.jpeg)|*.jpeg|All files (*.*)|*.*",
12 FilterIndex = 2
13 };
14
15 if (sfd.ShowDialog() == true)
16 {
17
18 Uri end1point = new Uri(imgUrl);
19 WebClient client = new WebClient();
20 client.OpenReadCompleted += (ss, ee) =>
21 {
22 Stream pngStream = ee.Result;
23 byte[] binaryData = new Byte[pngStream.Length];
24 pngStream.Read(binaryData, 0, (int)pngStream.Length);
25 Stream stream = sfd.OpenFile();
26 stream.Write(binaryData, 0, binaryData.Length);
27 stream.Close();
28
29 };
30 client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
31 client.OpenReadAsync(endpoint);
32 }
33
34 }
35
36 void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
37 {
38 //DownloadProgressChangedEventArgs.ProgressPercentage - 下载完成的百分比
39 //DownloadProgressChangedEventArgs.BytesReceived - 当前收到的字节数
40 //DownloadProgressChangedEventArgs.TotalBytesToReceive - 总共需要下载的字节数
41 //DownloadProgressChangedEventArgs.UserState - 用户标识
42
43 this.tbMsgString.Text = string.Format("完成百分比:{0} 当前收到的字节数:{1} 资料大小:{2} ",
44 e.ProgressPercentage.ToString() + "%",
45 e.BytesReceived.ToString(),
46 e.TotalBytesToReceive.ToString());
47
48 }
49
50 #endregion

2.2下载方法2

1  private void btnDownload_Click(object sender, RoutedEventArgs e)
2 {
3 System.Windows.Browser.HtmlPage.Window.Eval("window.location.href=‘http://localhost:51896/download.ashx?filename=IMG_20140329_093302.jpg‘;");
4 }

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5
6 namespace SilverlightApplication9.Web
7 {
8 /// <summary>
9 /// download 的摘要说明
10 /// </summary>
11 public class download : IHttpHandler
12 {
13 private long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
14 public void ProcessRequest(HttpContext context)
15 {
16 //string fileName = "123.jpg";//客户端保存的文件名
17 String fileName = context.Request.QueryString["filename"];
18 string filePath = context.Server.MapPath(@"Pics/IMG_20140329_093302.jpg");
19 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
20
21 if (fileInfo.Exists == true)
22 {
23 byte[] buffer = new byte[ChunkSize];
24 context.Response.Clear();
25 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
26 long dataLengthToRead = iStream.Length;//获得下载文件的总大小
27 context.Response.ContentType = "application/octet-stream";
28 //通知浏览器下载文件而不是打开
29 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
30 while (dataLengthToRead > 0 && context.Response.IsClientConnected)
31 {
32 int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
33 context.Response.OutputStream.Write(buffer, 0, lengthRead);
34 context.Response.Flush();
35 dataLengthToRead = dataLengthToRead - lengthRead;
36 }
37 context.Response.Close();
38 context.Response.End();
39 }
40 //context.Response.ContentType = "text/plain";
41 //context.Response.Write("Hello World");
42 }
43
44 public bool IsReusable
45 {
46 get
47 {
48 return false;
49 }
50 }
51 }
52 }

3.删除

 1  private void WebClientCommand(string isDeleteParam, int sort)
2 {
3 string uploadFileName = null;
4 WebClient webclient = new WebClient();
5 Uri upTargetUri = new Uri(String.Format("http://localhost:" + HtmlPage.Document.DocumentUri.Port + "/WebClientUpLoadStreamHandler.ashx?fileName={0}&result={1}", uploadFileName, isDeleteParam), UriKind.Absolute);
6 webclient.UploadStringCompleted += webclient_UploadStringCompleted;
7 webclient.UploadStringAsync(upTargetUri,"");
8
9
10
11 }

View
Code

1  void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
2 {
3 if (e.Error == null)
4 {
5 EasySL.Controls.Window.Alert("删除成功", this.floatePanel);
6 }
7 }

 1 using Huitu.Bjsq.Service;
2 using System;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Linq;
6 using System.Web;
7
8 namespace EasySL.Web
9 {
10 /// <summary>
11 /// WebClientUpLoadStreamHandler 的摘要说明
12 /// </summary>
13 public class WebClientUpLoadStreamHandler : IHttpHandler
14 {
15 public void ProcessRequest(HttpContext context)
16 {
17 //获取上传的数据流
18 string fileNameStr = context.Request.QueryString["fileName"];
19 string paramResult = context.Request.QueryString["result"];
20 Stream sr = context.Request.InputStream;
21 try
22 {
23 string filename = "";
24 filename = fileNameStr;
25 byte[] buffer = new byte[4096];
26 int bytesRead = 0;
27 if (!string.IsNullOrEmpty(paramResult))
28 {
29 foreach (string item in paramResult.Split(‘|‘))
30 {
31 string paramDel = context.Server.MapPath("FileLoad/" + item);
32 if (File.Exists(paramDel))
33 {
34 File.Delete(paramDel);
35 context.Response.ContentType = "text/plain";
36 context.Response.Write("删除成功");
37 }
38 }
39 }
40 else
41 {
42 //将当前数据流写入服务器端文件夹ClientBin下
43 string targetPath = context.Server.MapPath("FileLoad/" + filename);
44 using (FileStream fs = File.Create(targetPath, 4096))
45 {
46 while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
47 {
48 //向文件中写信息
49 fs.Write(buffer, 0, bytesRead);
50 }
51 }
52 context.Response.ContentType = "text/plain";
53 context.Response.Write("上传成功");
54 }
55 }
56
57 catch (Exception e)
58 {
59 context.Response.ContentType = "text/plain";
60 context.Response.Write("上传失败, 错误信息:" + e.Message);
61 }
62 finally
63 { sr.Dispose(); }
64 }
65
66 public bool IsReusable
67 {
68 get
69 {
70 return false;
71 }
72 }
73 }
74 }

4.对于处理上传大文件的处理

1 <configuration>
2 <system.web>
3 <compilation debug="true" targetFramework="4.5" />
4 <httpRuntime targetFramework="4.5" maxRequestLength="21048576" executionTimeout="7200" />
5 </system.web>
6 </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中的绝对路径,修改为相对路径

silverlight webclient实现上传、下载、删除操作

时间: 2024-10-12 13:12:58

silverlight webclient实现上传、下载、删除操作的相关文章

java操作FTP,实现文件上传下载删除操作

上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端口请写-1 * @param username FTP登录账号 * @param password FTP登录密码 * @param path FTP服务器保存目录 * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回t

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

前言 为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下. 本文足如有不足之处,请在下方留言提出,我会进行改正的,谢谢! 搭建IIS文件服务器 本博文使用的操作系统为Windows 10 企业版,其他Windows系统类似,请借鉴: 一.当然,开始肯定没有IIS,那该怎么办?需要一个软件环境进行搭建,具体方法如下: 1)打开“控制面板”,找到“程序与功能”,如

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

在使用WebClient类之前,必须先引用System.Net命名空间,文件下载.上传与删除的都是使用异步编程,也可以使用同步编程, 这里以异步编程为例: 1)文件下载: static void Main(string[] args) { //定义_webClient对象 WebClient _webClient = new WebClient(); //使用默认的凭据--读取的时候,只需默认凭据就可以 _webClient.Credentials = CredentialCache.Defau

【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

和上一份简单 上传下载一样 来,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html API拿走不谢!!! 1.FTP配置实体 1 package com.agen.util; 2 3 public class FtpConfig { 4 //主机ip 5 private String FtpHost = "192.168.18.252&quo

apache FtpClient上传下载删除文件夹及文件

/* * 文件名:FtpUtil.java * 描述:FTP操作 * 修改时间2014-08-10 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import jav

图片上传-下载-删除等图片管理的若干经验总结

图片上传功能很常见,很多人都觉得这个功能很简单,随着要求的提高,这个图片小系统也真是复杂啊. 需求1: 上传,未了达到"大容量存储"."负载均衡"."性能好","有技术含量"等装逼需求,采用了Fastdfs. 注:FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理. 功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等,解决了大容量存储和负载均衡的问题. 特别适合以文件为载体的在线服务,如相册网站.视频

Springmvc file多附件上传 显示 删除操作

之前项目需求要做一个多附件上传 并显示上传文件 带删除操作 一筹莫展之际搜到某个兄弟发的博客感觉非常好用被我copy下来了此贴算是改良版 再次感谢(忘记叫什么了时间也有点久没有历史记录了)先上图 基于springmvc附件上传 所需jar包 commons.fileupload-1.2.0.jar commons.io-1.4.0.jar 这个是我使用的jar包有需要的可以直接百度网盘下载 里面有好几个版本 自行选择 放在lib下面 使用的话maven 直接下载也可以 链接:https://pa

Struts2 文件上传,下载,删除

本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用FileUtil上传 6.使用IOUtil上传 7.使用IOUtil上传 8.使用数组上传多个文件 9.使用List上传多个文件 ----1.基于表单的文件上传----- fileupload.jsp <body> <form action="showFile.jsp" na

C# WebClient 实现上传下载网络资源

下载数据 WebClient wc = new WebClient();1 string str= wc.DownloadString("地址")://直接下载字符串 2 wc.DownloadFile("addredd", "fileName");//下载文件 并指定下载到的地址 3  byte[] b=wc.DownloadData("address")//直接返回一个二进制数组 然后进行转换 wc.Dispose();