热门关键字:
jquery > jquery教程 > jquery教程 > asp.net文件下载,实现隐藏文件下载地址

asp.net文件下载,实现隐藏文件下载地址

295
作者:管理员
发布时间:2021/2/4 11:13:02
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=3819
文件下载其实很简单。最简单的方式就是直接用a标签指向文件地址,但是这种方式暴露了文件的地址,不适合做积分下载。同时,如果文件为图片或者xml文件的话浏览器默认是打开文件而不是弹出下载窗口。
第二种就是用js实现。
function getFile(id) {
    jQuery.ajax({
        type: "POST",
        dataType: "json",
        timeout: 3000,
        url: "/upload/ajax.aspx?act=getfile&r=" + Math.random(),
        data: { "id": id },
        beforeSend: function () {
        },
        success: function (data) {
            if (data.statu != "ok") {
                alert(data.msg);
            }
            else {
                window.location.href = data.res;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(alert(textStatus));
        }
    });
}
这种的原理也跟第一种是一样的。虽然实现了隐藏下载地址,但是,同样的如果文件是图片也会出现第一中方式中提到的问题。
第三中就是通过服务器端更改Response 的Header实现文件的下载。
// GET: /Downoad/
        public ActionResult Index() {
 
            #region 文件下载
            var filePath = Server.MapPath("/images/Razor.pdf");//文件地址
            FileInfo fi = new FileInfo(filePath);
            Response.ClearHeaders();
            Response.AppendHeader("Content-Disposition", "attachment;filename="
                //将文件名改成Guid
                + string.Format("{0:n}{1}", System.Guid.NewGuid(), fi.Extension));
            //文件的大小
            Response.AddHeader("Content-Length", fi.Length.ToString());
            Response.AppendHeader("Last-Modified", fi.LastWriteTime.ToFileTime().ToString());
            Response.AppendHeader("Location", Request.Url.AbsoluteUri);
            //文件的类型。如:pdf文件为:"application/pdf",
            //此处为"application/unknown" 未知类型(浏览器会根据文件类型自动判断)
            Response.ContentType = "application/unknown";
            Response.WriteFile(filePath);
            #endregion
            //Response.End();
            return View();
        }





如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jQuery
友荐云推荐