javascript下载文件几种方式,接收后台返回流下载或直接下载文件 您所在的位置:网站首页 后端文件下载 javascript下载文件几种方式,接收后台返回流下载或直接下载文件

javascript下载文件几种方式,接收后台返回流下载或直接下载文件

2024-01-21 16:24| 来源: 网络整理| 查看: 265

目录

1 javascript下载文件7中方式

1.1 window.location.href下载

1.2 window.location下载

1.3 iframe下载

1.4 form表单的形式下载

1.5 a标签的方式下载

1.6 ajax方式后台返回文件流下载

1.7 axios方法后台返回流方式下载

 2.完整源码

1 javascript下载文件7中方式 1.1 window.location.href下载 /** *window.location.href下载 */ function btn1() { debugger; window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; } 1.2 window.location下载 /** *window.location下载 */ function btn2() { debugger; window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile'; } 1.3 iframe下载 /*** *iframe下载 */ function btn3() { try { var elementIF = document.createElement("iframe"); elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; elementIF.style.display = "none"; document.body.appendChild(elementIF); }catch(error) { console.log(error); } } 1.4 form表单的形式下载 /** *form表单的形式下载 */ function btn4() { const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; var form = $(""); form.attr("style", "display:none"); /**target 属性规定一个名称或一个关键词,指示在何处打开 action URL, * 即在何处显示提交表单后接收到的响应。 * *_blank 在新窗口/选项卡中打开。 *_self 在同一框架中打开。(默认) *_parent 在父框架中打开。 *_top 在整个窗口中打开。 *framename 在指定的 iframe 中打开。 */ form.attr("target", "_self"); form.attr("method", "get"); form.attr("action", url); $("body").append(form); // 提交 form.submit(); } 1.5 a标签的方式下载 /** *a标签的方式下载 **/ function btn5() { const fileName = "Benjamin_Download_Test_File.pdf"; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; var a = document.createElement("a"); a.download = fileName; a.href = url; // 修复firefox中无法触发click $("body").append(a) a.click(); $(a).remove(); } 1.6 ajax方式后台返回文件流下载 /** * *ajax方式后台返回文件流下载、 *success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。 * *关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'}, */ function btn6() { debugger; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; $.ajax({ url: url, type: 'get', data: {}, contentType: 'application/json;charset=utf-8', // 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据 dataType: 'binary', // 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流 xhrFields: {responseType: 'blob'}, success: function(result, status, xhr) { const fileName = "Benjamin_Download_Test_File_20221225.pdf"; // 可通过XMLHttpRequest对象,获取响应头 console.log(xhr); // 浏览器兼容 参数Blob类型 const downloadURL = (window.URL || window.webkitURL).createObjectURL(result); // 创建a标签 var a = document.createElement('a'); // 下载后文件的名字 a.download = fileName; a.href = downloadURL; document.body.appendChild(a); a.click(); setTimeout(function () { // 移除内存中的临时文件路径和为下载而创建的a标签 URL.revokeObjectURL(downloadURL); a.remove(); }, 10000); }, error: function (xhr, textStatus, errorMessage) { // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码 const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo")); // 对错误信息进行打印 console.log(errorInfo); } }); } 1.7 axios方法后台返回流方式下载 /** *axios方法后台返回流方式下载 */ function btn7() { debugger; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; const fileName = "Benjamin_Download_Test_File_20221225.pdf"; this.axios.get(url, {responseType: 'blob'}).then(response => { // 创建a标签 let a = document.createElement("a"); a.download = fileName; // 创建二进制对象 const blob = new Blob([response.data]); const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob); a.href = downloadURL; // 模拟点击 a.click(); //释放资源并删除创建的a标签 URL.revokeObjectURL(downloadURL);// a.href document.body.removeChild(a); }).catch(error => { console.log(error); }); }

下载按钮: 

 都可以成功下载:

 2.完整源码

后台简单源码:

@RestController @RequestMapping("/flower/beetl") @CrossOrigin public class BeetlController { @GetMapping(value = "/downloadFile") public void downloadFile(HttpServletResponse httpServletResponse) { File file = new File("C:\\Users\\admin\\Desktop\\download\\Benjamin_Download_Test_File.pdf"); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(file); os = httpServletResponse.getOutputStream(); httpServletResponse.setContentType("application/octet-stream"); httpServletResponse.setHeader("Content-Disposition", "attachment;fileName=Benjamin_Download_Test_File.pdf"); int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1) { os.write(bytes, 0, bytes.length); os.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }

 html页面源码:

7中下载方式 window.location.href下载 window.location下载 iframe下载 form表单的形式下载 a标签的方式下载 ajax方式后台返回文件流下载 axios方法后台返回流方式下载 /** *window.location.href下载 */ function btn1() { debugger; window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; } /** *window.location下载 */ function btn2() { debugger; window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile'; } /*** *iframe下载 */ function btn3() { try { var elementIF = document.createElement("iframe"); elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; elementIF.style.display = "none"; document.body.appendChild(elementIF); }catch(error) { console.log(error); } } /** *form表单的形式下载 */ function btn4() { const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; var form = $(""); form.attr("style", "display:none"); /**target 属性规定一个名称或一个关键词,指示在何处打开 action URL, * 即在何处显示提交表单后接收到的响应。 * *_blank 在新窗口/选项卡中打开。 *_self 在同一框架中打开。(默认) *_parent 在父框架中打开。 *_top 在整个窗口中打开。 *framename 在指定的 iframe 中打开。 */ form.attr("target", "_self"); form.attr("method", "get"); form.attr("action", url); $("body").append(form); // 提交 form.submit(); } /** *a标签的方式下载 **/ function btn5() { const fileName = "Benjamin_Download_Test_File.pdf"; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; var a = document.createElement("a"); a.download = fileName; a.href = url; // 修复firefox中无法触发click $("body").append(a) a.click(); $(a).remove(); } /** * *ajax方式后台返回文件流下载、 *success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。 * *关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'}, */ function btn6() { debugger; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; $.ajax({ url: url, type: 'get', data: {}, contentType: 'application/json;charset=utf-8', // 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据 dataType: 'binary', // 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流 xhrFields: {responseType: 'blob'}, success: function(result, status, xhr) { const fileName = "Benjamin_Download_Test_File_20221225.pdf"; // 可通过XMLHttpRequest对象,获取响应头 console.log(xhr); // 浏览器兼容 参数Blob类型 const downloadURL = (window.URL || window.webkitURL).createObjectURL(result); // 创建a标签 var a = document.createElement('a'); // 下载后文件的名字 a.download = fileName; a.href = downloadURL; document.body.appendChild(a); a.click(); setTimeout(function () { // 移除内存中的临时文件路径和为下载而创建的a标签 URL.revokeObjectURL(downloadURL); a.remove(); }, 10000); }, error: function (xhr, textStatus, errorMessage) { // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码 const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo")); // 对错误信息进行打印 console.log(errorInfo); } }); } /** *axios方法后台返回流方式下载 */ function btn7() { debugger; const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile"; const fileName = "Benjamin_Download_Test_File_20221225.pdf"; this.axios.get(url, {responseType: 'blob'}).then(response => { // 创建a标签 let a = document.createElement("a"); a.download = fileName; // 创建二进制对象 const blob = new Blob([response.data]); const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob); a.href = downloadURL; // 模拟点击 a.click(); //释放资源并删除创建的a标签 URL.revokeObjectURL(downloadURL);// a.href document.body.removeChild(a); }).catch(error => { console.log(error); }); } button{ width:200px; height:35px; }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有