一般处理程序下载

方式有很多

一般处理程序可以直接通过a标签访问

 最近项目里用ashx制作了一个下载服务,实现不难,但是记录的元素比较繁琐,所以写篇心得分享记录下

      一.制作服务前的准备:

         1.要下载的文件在服务器上的路径,下文用SPath代替

         2.要下载的文件在被下载时候显示的文件名,下文用SName代替

      二.制作ASHX服务:

         1.  context.Response.ContentType = "application/octet-stream";

              设置响应的返回类型是文件流

         2. context.Response.AddHeader("content-disposition", "attachment;filename=SName");

              设置相应的头以及被下载时候显示的文件名

         3.System.IO.FileInfo lFileInfo = new System.IO.FileInfo(lPath);  
               获取下载文件的文件流

         4. context.Response.WriteFile(lFileInfo.FullName);

               返回要下载的文件流

         5. context.Response.End();

                关闭响应

       三.如何使用服务

         在html中创建个A标签,在href属性中指向该服务,即可实现下载功能

 

      这是目前找到的比较方便的下载文件方法,如果有更方便的,请大家推广下

        

 

方法二 

当直接返回一个地址window.open的时候,有时候文件会被直接打开

解决方法

window.open('downFile.aspx?rowUrl=' + ServerIP + tempArray[index]);

string filePath = Request.QueryString["rowUrl"];

if (filePath.Contains("."))
{
string fileName = filePath.Substring(filePath.LastIndexOf('/') + 1);
string strP = filePath.Substring(filePath.IndexOf('/',10));
string SerPath = Server.MapPath("~" + strP);
//以字符流的形式下载文件
FileStream fs = new FileStream(SerPath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

}

posted @ 2016-09-21 21:45  好好學習  阅读(848)  评论(0编辑  收藏  举报