silverlight文件下载方法

来源:互联网 发布:苹果茶软件 编辑:程序博客网 时间:2024/06/02 23:31
silverlight来实现文件下载,纠结了很长的时间。一般的,如果是zip、rar等文件,直接通过NavigationService.Navigate(url);的形式即可,但是,如果是wav、MP3文件等,浏览器往往会直接打开应用程序进行播放(如Windows Media Player等),造成了很多的困惑。

网上搜索的解决方案,要么是通过silverlight客户端来下载,要么通过asp.net来下载,不一而足,各有优缺点。这里不评价各种优缺点,只记述了自己实现的结果。这里需要下载的文件是存放在服务器上的,并考虑到了虚拟目录的。一些动态生成的文件,也可以以此处理。

asp.net端的代码,短短的,没有几行:

public void ProcessRequest(HttpContext context){string filename = context.Request.QueryString["filename"];string physical_file_name = context.Server.MapPath(filename);FileInfo fi = new FileInfo(physical_file_name);//context.Response.Output.WriteLine("物理文件名:" + physical_file_name);context.Response.Clear();context.Response.ContentType = "application/octet-stream";//通知浏览器下载文件而不是打开context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + fi.Name);context.Response.WriteFile(physical_file_name);}

silverlight端的处理:

NavigationService.Navigate(url);