赞
踩
目录
- /**
- *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>");
- 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);
- });
-
- }
下载按钮:
都可以成功下载:
后台简单源码:
- @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页面源码:
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>7中下载方式</title>
- </head>
-
- <body>
- <div style="margin-left:60px;margin-top:20px">
- <button id="btn1" onclick="btn1()" style="background-color:red" >window.location.href下载</button><br> <br>
- <button id="btn2" onclick="btn2()" style="background-color:orange">window.location下载</button><br> <br>
- <button id="btn3" onclick="btn3()" style="background-color:yellow">iframe下载</button><br> <br>
- <button id="btn4" onclick="btn4()" style="background-color:green">form表单的形式下载</button><br> <br>
- <button id="btn5" onclick="btn5()" style="background-color:cyan">a标签的方式下载</button><br> <br>
- <button id="btn6" onclick="btn6()" style="background-color:blue">ajax方式后台返回文件流下载</button><br> <br>
- <button id="btn7" onclick="btn7()" style="background-color:purple">axios方法后台返回流方式下载</button><br> <br>
- </div>
-
- </body>
- <!-- <script th:src="@{js/jquery.min.js}"></script> -->
- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
-
-
- <script>
-
- /**
- *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>");
- 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);
- });
-
- }
-
-
- </script>
-
- <style>
- button{
- width:200px;
- height:35px;
- }
-
- </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。