8,737
社区成员
发帖
与我相关
我的任务
分享
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
//向指定的Url发送下载流数据请求
String imgUrl = "http://localhost/Pics/aa.jpg";
Uri endpoint = new Uri(imgUrl);
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted);
// client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
client.OpenReadAsync(endpoint);
}
void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
//OpenReadCompletedEventArgs.Error - 该异步操作期间是否发生了错误
//OpenReadCompletedEventArgs.Cancelled - 该异步操作是否已被取消
//OpenReadCompletedEventArgs.Result - 下载后的 Stream 类型的数据
//OpenReadCompletedEventArgs.UserState - 用户标识
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
return;
}
if (e.Cancelled != true)
{
// 获取下载的流数据(在此处是图片数据)并显示在图片控件中
Stream stream = e.Result;
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
imgDownLoad.Source = bitmap;
}
}
Uri upTargetUri = new Uri(String.Format("http://localhost/WebClientDownHandler.ashx?filename={0}", imgUrl), UriKind.Absolute); //指定上传地址
WebRequest request = WebRequest.Create(upTargetUri);
request.Method = "GET";
request.ContentType = "application/octet-stream";
request.BeginGetResponse(new AsyncCallback(RequestReady), request);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace USTCORi.WebLab.Service
{
public class WebClientDownHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
String fileName = context.Request.QueryString["filename"]; //客户端保存的文件名
String filePath = context.Server.MapPath("Pics/" + fileName); //路径
//string fileName = context.Request.QueryString["filename"];
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
byte[] buffer = new byte[102400];
context.Response.Clear();
FileStream iStream = 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 > 0 && context.Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'读取的大小
context.Response.OutputStream.Write(buffer, 0, lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
context.Response.Close();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}