码迷,mamicode.com
首页 > Windows程序 > 详细

C#根据path文件地址进行下载

时间:2016-11-15 16:51:17      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:oct   write   exce   down   方法   gets   path   convert   mba   

1:在js文件中写入加密方法

var Comm = {
    encode: function (text) {
        if (text)
            return new Base64().encode(text);
        else
            return text;
    }

}

2:Handler类中返回文件地址:

 如:string path = "/Files/审理意见书.doc";

3:在js方法中接收并跳转页面进行下载

function Download(){
      $.post(‘ ‘,{action:‘ ‘},function(data){

    if(path!=""){

      window.location.href="/Download.aspx?P="+Comm.encode(path);

    }

  });
   }

4:在Download.aspx也进行后台代码操作

    a:首先写入解密方法

 public  static string Decrypt(string text) {

  byte[] bytes = Convert.FromBase64String(text);

  return Encoding.UTF8.GetString(bytes);

 }

    b:进行文件解析以及下载操作

 protected void Page_Load(object sender, EventArgs e) {

     string path = Decrypt(Parse.ToString(Request["p"]).Replace(" ", "+"));

     string fileName = path.Substring(path.LastIndexOf(‘/‘) + 1);

     var filePath = HttpContext.Current.Server.MapPath(path);

     try {

        //判断是否存在此文件

        if (File.Exists(filePath)) {

          FileStream io = File.Open(filePath, FileMode.Open);

          long fileSize = io.Length;
                       byte[] filebit = new byte[(int) fileSize];
                         io.Read(filebit, 0, (int) fileSize);
                       Response.Clear();
                       fileName = HttpUtility.UrlEncode(fileName);
                       Response.ContentType = "application/octet-stream";
                       Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
                       Response.BinaryWrite(filebit);
                       io.Dispose();
                       Response.Flush();
                       Response.End();

        } else {
                        Response.Clear();
                        Response.Write("<script type=\"text/javascript\" src=\"/Scripts/jquery-1.10.2.js\"></script><script>$(function () {alert(‘文件不存在或已被删除‘, { icon: 0 }, function () { window.close(); }, function () { window.close(); });});</script>");
                }

     }catch (Exception ex) {
                Response.Clear();
                Response.Write("<script type=\"text/javascript\" src=\"/Scripts/jquery-1.10.2.js\"></script> <script>$(function () {alert(‘" + ex.Message + "‘, { icon: 0 }, function () { window.close(); }, function () { window.close(); });});</script>");
            }

  }

 

C#根据path文件地址进行下载

标签:oct   write   exce   down   方法   gets   path   convert   mba   

原文地址:http://www.cnblogs.com/recent/p/6066054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!