ajax 实现文件下载功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010271602/article/details/77663760

ajax一般是用来请求服务端的数据,下载文件需要先从服务器获取文件请求路径,然后使用form表单提交的方法来实现文件的下载。

先引入jquery文件,jquery的免费cdn地址:<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
// 定义到jQuery全局变量下-文件下载
jQuery.download = function (url, method, filedir) {
  jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' +  // action请求路径及推送方法
              '<input type="text" name="filePath" value="' + filedir + '"/>' + // 文件路径
          '</form>')
  .appendTo('body').submit().remove();
  //var newTab = window.open('about:blank')
  //newTab.location.href = url;
};
使用:

//导出事件
            $('#btnExport').click(function (e) {
                e.preventDefault();//阻止a链接的跳转行为
                $.ajax({
                    type: "post",
                    url: "/FileExport/Export",
                    dataType: "json",
                    data: { address: addr},
                    success: function (data) {
                        $.download('/FileExport/DownLoadFile', 'post', data.value); // 下载文件
                    },
                    error: function (data) {
                        alert("对不起,出现错误,请稍后重试或联系管理员");
                    }
                });
            });



猜你喜欢

转载自blog.csdn.net/u010271602/article/details/77663760
今日推荐