页面:hlink.NavigateUri = new Uri(ServiceHelper.BaseUrl + ServicePath.DownFilePath + "?fileName="+((Sys_AttachmentLibraryModel)selDownFile.SelectedItem).FileUrl.ToString());
服务端:DownLoadFileHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
public class DownLoadFileHandler : BaseService
{
public override void ProcessRequest(HttpContext context)
{
Context = context;
Result = new ActionResult();
String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名
fileName = HttpUtility.UrlDecode(fileName);
String filePath = ConfigHelper.UploadPath+ 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.Substring(fileName.LastIndexOf("\\")+1), 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();
}
// 输出结果
OutputResult();
}
}
本文详细介绍了如何使用C#编程语言实现一个文件下载服务,包括从客户端获取文件名,构建完整路径,并通过HTTP响应将文件以流的形式发送给客户端。
112

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



