1
// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
2
// 输入参数 _Request: Page.Request对象, _Response: Page.Response对象, _fileName: 下载文件名, _fullPath: 带文件名下载路径, _speed 每秒允许下载的字节数
3
// 返回是否成功
4
public static bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed)
5
{
6
try
7
{
8
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
9
BinaryReader br = new BinaryReader(myFile);
10
try
11
{
12
_Response.AddHeader("Accept-Ranges", "bytes");
13
_Response.Buffer = false;
14
long fileLength = myFile.Length;
15
long startBytes = 0;
16
17
int pack = 102400; //10K bytes
18
//int sleep = 200; //每秒5次 即5*10K bytes每秒
19
int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
20
if (_Request.Headers["Range"] != null)
21
{
22
_Response.StatusCode = 206;
23
string[] range = _Request.Headers["Range"].Split(new char[] {'=', '-'});
24
startBytes = Convert.ToInt64(range[1]);
25
}
26
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
27
if (startBytes != 0)
28
{
29
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
30
}
31
_Response.AddHeader("Connection", "Keep-Alive");
32
_Response.ContentType = "application/octet-stream";
33
_Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );
34
35
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
36
int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;
37
38
for (int i = 0; i < maxCount; i++)
39
{
40
if (_Response.IsClientConnected)
41
{
42
_Response.BinaryWrite(br.ReadBytes(pack));
43
Thread.Sleep(sleep);
44
}
45
else
46
{
47
i=maxCount;
48
}
49
}
50
}
51
catch
52
{
53
return false;
54
}
55
finally
56
{
57
br.Close();
58
myFile.Close();
59
}
60
}
61
catch
62
{
63
return false;
64
}
65
return true;
66
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66
