2014-02-21 49 views
0

谁能请解释一下这个代码下载代码expalanation

if (e.CommandName == "download") 
      { 
       string filename = e.CommandArgument.ToString(); 
       string path = MapPath("~/Docfiles/" + filename); 
       byte[] bts = System.IO.File.ReadAllBytes(path); 
       Response.Clear(); 
       Response.ClearHeaders(); 
       Response.AddHeader("Content-Type", "Application/octet-stream"); 
       Response.AddHeader("Content-Length", bts.Length.ToString()); 
       Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); 
       Response.BinaryWrite(bts); 
       Response.Flush(); 
       Response.End(); 
      } 

是什么命令参数,MapPath的,也这是什么 “内容类型”,“应用程序/八位字节流” 也

Response.AddHeader("Content-Length", bts.Length.ToString()); 
       Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); 
       Response.BinaryWrite(bts); 
       Response.Flush(); 
+1

您可以尝试谷歌条款。 – Ofiris

+0

我是如何找到这段代码的范围的..我没有发现这就是为什么我在这里发布 – user3338484

+0

这是不言自明的。它是在用户单击按钮时下载文件。该文件位于应用程序根目录(〜/是应用程序根目录的简写)/ DocFiles目录中。当一个文件即时生成时,您通常会看到这种代码。 – Tim

回答

0

首先,我建议您使用MSDN documentation来搜索有关您想了解更多关于对象和方法的更多信息。 MSDN是一个有用的网络,应该使用。

引用MSDN CommandArgument:“获取或设置传递给Command事件的可选参数以及关联的CommandName”。它用于获取传递给命令事件的参数。在这种情况下,它是文件名。

string filename = e.CommandArgument.ToString(); 

MapPath用于将指定路径映射到物理路径。使用这个你可以得到文件的真实路径。例如: “C:\ DocFiles会\ Yourfile.pdf”

string path = MapPath("~/Docfiles/" + filename); 

ReadAllBytes方法,打开一个文件,读取内容,然后关闭该文件。这会将该文件的内容作为字节数组返回。

byte[] bts = System.IO.File.ReadAllBytes(path); 

Response对象用于从服务器向用户发送输出。

Response.Clear(); 
Response.ClearHeaders(); 

Response.AddHeader用于构建将发回给用户的响应头。我们使用它来设置关于我们发送回客户端的数据的信息。 “Content-Type”属性用于指定您要返回给用户的文件类型。

Response.AddHeader("Content-Type", "Application/octet-stream"); 

“Content-Length”属性用于通知浏览器您要返回的文件的大小。

Response.AddHeader("Content-Length", bts.Length.ToString()); 

“Content-Disposition”用于通知将要返回的文件的名称。例如“file1.doc” Response.AddHeader(“Content-Disposition”,“attachment; filename =”+ filename); “BinaryWrite()”将您的文件(此时,谁是字节数组格式)写入当前HTTP输出,而不进行任何字符转换。

Response.BinaryWrite(bts); 

Flush方法立即发送缓冲输出。

Response.Flush(); 

最后,导致服务器停止处理请求并返回当前结果。

Response.End(); 
0

如果命令是下载,最有可能从一个网格按钮,然后拿到文件作为参数(这是一个按钮控件属性)的名称,并将其发送给浏览器。这会提示用户下载文件。