js 通过URL下载PDF文件(兼容PC端、移动端大部分浏览器)

 

在网上找了好多资料,最后总结下自己的实现方案,废话不多说,直接上代码

 

一、 第一种,后台服务器有静态资源且是固定的文件名(GET方式下载文件)

window.location.href="http://www.域名/template.xlsx(文件名)"

二、第二种,后台返回单文件流,前台进行读取保存

1、前端代码

/**
 * 文件下载(from表单通过文件URL单文件下载支持移动端安卓/苹果手机)
 * @param url
 */
function downloadFileForm(url) {
    var filename = url.substr(url.lastIndexOf('/') + 1);
    var $downForm = $("
"); $downForm.attr("action", '/downLoad/getdownLoadFile.do'); var $input = $(""); $input.attr("name", "fileUrl"); $input.val(url); $downForm.append($input); $(document.body).append($downForm); //提交表单,实现下载 $downForm.submit(); $downForm.remove(); } /** * 文件下载(支持PC端批量及移动端部分机型批量下载) * @param url */ function downloadFileBatch(url) { var filename = url.substr(url.lastIndexOf('/') + 1); //移动端 if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){ //支持Android,不支持iPhone,iPhone可以考虑下载zip包 window.open(url); }else { var oReq = new XMLHttpRequest(); var URLToPDF = '/downLoad/getdownLoadFile.do?businessOrderNo=' + sessionStorage.getItem("businessOrderNo") + '&fileUrl=' + encodeURIComponent(url); oReq.open("GET", URLToPDF, true); oReq.setRequestHeader("Content-Type", 'application/octet-stream;charset=utf-8'); oReq.responseType = "blob"; oReq.onload = function() { if (oReq.status === 200) { var blob = new Blob([oReq.response], { type: 'application/force-download;charset=utf-8' }); if (window.navigator.msSaveBlob) { window.navigator.msSaveBlob(blob, filename); } else { // var file = new Blob([oReq.response], { // type: 'application/pdf' // }); saveAsPDF(blob, filename); } } }; oReq.send(); } } /** * 批量保存(续) * @param data * @param name */ function saveAsPDF(data, name) { var urlObject = window.URL || window.webkitURL || window; var export_blob = new Blob([data]); var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = urlObject.createObjectURL(export_blob); save_link.download = name; save_link.click(); urlObject.revokeObjectURL(export_blob); }

2、后端代码

    /**
     * 下载文件
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getdownLoadFile.do", method = RequestMethod.GET)
    public void getdownLoadFile(HttpServletRequest request, HttpServletResponse response) {
        InputStream txtIn = null;
        OutputStream os = null;
        try {
            //获取文

你可能感兴趣的:(前端,java,javascript,html5,jquery)