1 对于下载时新打开一窗口下载,下载完后需要关闭的
2 一种:对于较小文件可以有效:
3 System.IO.FileInfo file = new System.IO.FileInfo("F:\mp3\mp3\别哭我最爱的人.mp3");
4 Response.Clear();
5 Response.ClearHeaders();
6 Response.Buffer = false;
7 Response.Charset="GB2312";
8 Response.ContentEncoding=System.Text.Encoding.UTF8;
9 Response.ContentType = "application/octet-stream";
10
11 Response.AddHeader("Content-Disposition", "attachment; filename="+Server.UrlEncode("别哭我最爱的人.mp3"));
12 Response.AddHeader("Content-Length", file.Length.ToString());
13
14 Response.WriteFile(file.FullName);
15 Response.Flush();
16 Response.End();
17 该代码可以实现输出文件并将新打开的窗体关闭。
18 另一种对于大文件,我们用上述代码不是较好,因为上述代码是将文件全缓存于服务器后才输出的,如果你的服务器流量大,且文件较大,不建议用以上方法。
19 以下我测试过,较好能解决:
20 public static bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed)
21 {
22 try
23 {
24 FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
25 BinaryReader br = new BinaryReader(myFile);
26 try
27 {
28 _Response.AddHeader("Accept-Ranges", "bytes");
29 _Response.Buffer = false;
30 long fileLength = myFile.Length;
31 long startBytes = 0;
32
33 int pack = 10240; //10K bytes
34 int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
35 if (_Request.Headers["Range"] != null)
36 {
37 _Response.StatusCode = 206;
38 string[] range = _Request.Headers["Range"].Split(new char[] {'=', '-'});
39 startBytes = Convert.ToInt64(range[1]);
40 }
41 _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
42 if (startBytes != 0)
43 {
44 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
45 }
46 _Response.AddHeader("Connection", "Keep-Alive");
47 _Response.ContentType = "application/octet-stream";
48 _Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );
49
50 br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
51 int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;
52 for (int i = 0; i < maxCount; i++)
53 {
54 if (_Response.IsClientConnected)
55 {
56 _Response.BinaryWrite(br.ReadBytes(pack));
57 Thread.Sleep(sleep);
58 }
59 else
60 {
61 i=maxCount;
62 }
63 }
64 _Response.Flush();
65 }
66 catch
67 {
68 return false;
69 }
70 finally
71 {
72 br.Close();
73 myFile.Close();
74 }
75 }
76 catch
77 {
78 return false;
79 }
80 return true;
81 }
82 这一种代码也是借签网上的
83 它也可以实现输出文件并关闭新打开幕窗体
84 另外在测试当中发现,服务器端与客户的操作系统不同
85 也会有一些意想不到的事情发生
86 一般来说,用以上代码,如不能正常关闭,你可以查阅浏览器的设置,在高级中。
87 再者,你可以修改不同的输出内容类型Response.ContentType = "application/octet-stream";因为不同的contenttype,在客户的端的解释可能是不一样的。