如何实现跨服务器下载文件呢?其实思路很简单,可以使用WebClient对象,将指定的文件从存储资源的服务器上下载一个副本到本地服务器,
再将本地的副本传输给请求的客户端。
下面上代码:
/// <summary>
/// 下载
/// </summary>
protected void DownLoadRecordFile()
{
//文件路径
string strPath = ConfigurationManager.AppSettings["filesource"].ToString() + Request.QueryString["FleNm"];
if (strPath.Length > 0)
{
string filename = strPath.Substring(strPath.LastIndexOf(@"/") + 1);
Page.Response.Clear();
ResFile(strPath, filename);
}
else
{
Response.Write("没有可下载的文件![<a href='javascript:window.close();'>关闭窗口</a>]");
}
Page.Response.End();
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
private void ResFile(string path, string fileName)
{
System.Uri remoteUri = new Uri(path);
//本地下载路径地址
string localurl = Server.MapPath("~/Document/" + fileName);
System.Net.WebClient myWebClient = new System.Net.WebClient();
FileInfo file = new FileInfo(localurl);
try
{
//判断本地路径下是否已存在(已有人查看下载过)
if (!(File.Exists(file.ToString())))
{
myWebClient.DownloadFileCompleted += (s, e) =>
{
//以流形式将本地对远程的副本输出
FileInfo fileinfo = new FileInfo(localurl);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "20%"));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
};
myWebClient.DownloadFileAsync(remoteUri, localurl);
}
else
{
//以流形式将本地对远程的副本输出
FileInfo fileinfo = new FileInfo(localurl);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "20%"));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
}
catch { }
}

2000

被折叠的 条评论
为什么被折叠?



