当前位置:   article > 正文

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

js 下载文件

目录

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下载

  1. /**
  2. *window.location.href下载
  3. */
  4. function btn1() {
  5. debugger;
  6. window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  7. }

1.2 window.location下载

  1. /**
  2. *window.location下载
  3. */
  4. function btn2() {
  5. debugger;
  6. window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile';
  7. }

1.3 iframe下载

  1. /***
  2. *iframe下载
  3. */
  4. function btn3() {
  5. try {
  6. var elementIF = document.createElement("iframe");
  7. elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  8. elementIF.style.display = "none";
  9. document.body.appendChild(elementIF);
  10. }catch(error) {
  11. console.log(error);
  12. }
  13. }

1.4 form表单的形式下载

  1. /**
  2. *form表单的形式下载
  3. */
  4. function btn4() {
  5. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  6. var form = $("<form>");
  7. form.attr("style", "display:none");
  8. /**target 属性规定一个名称或一个关键词,指示在何处打开 action URL,
  9. * 即在何处显示提交表单后接收到的响应。
  10. *
  11. *_blank 在新窗口/选项卡中打开。
  12. *_self 在同一框架中打开。(默认)
  13. *_parent 在父框架中打开。
  14. *_top 在整个窗口中打开。
  15. *framename 在指定的 iframe 中打开。
  16. */
  17. form.attr("target", "_self");
  18. form.attr("method", "get");
  19. form.attr("action", url);
  20. $("body").append(form);
  21. // 提交
  22. form.submit();
  23. }

1.5 a标签的方式下载

  1. /**
  2. *a标签的方式下载
  3. **/
  4. function btn5() {
  5. const fileName = "Benjamin_Download_Test_File.pdf";
  6. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  7. var a = document.createElement("a");
  8. a.download = fileName;
  9. a.href = url;
  10. // 修复firefox中无法触发click
  11. $("body").append(a)
  12. a.click();
  13. $(a).remove();
  14. }

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

  1. /**
  2. *
  3. *ajax方式后台返回文件流下载、
  4. *success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。
  5. *
  6. *关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'},
  7. */
  8. function btn6() {
  9. debugger;
  10. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  11. $.ajax({
  12. url: url,
  13. type: 'get',
  14. data: {},
  15. contentType: 'application/json;charset=utf-8',
  16. // 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据
  17. dataType: 'binary',
  18. // 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流
  19. xhrFields: {responseType: 'blob'},
  20. success: function(result, status, xhr) {
  21. const fileName = "Benjamin_Download_Test_File_20221225.pdf";
  22. // 可通过XMLHttpRequest对象,获取响应头
  23. console.log(xhr);
  24. // 浏览器兼容 参数Blob类型
  25. const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
  26. // 创建a标签
  27. var a = document.createElement('a');
  28. // 下载后文件的名字
  29. a.download = fileName;
  30. a.href = downloadURL;
  31. document.body.appendChild(a);
  32. a.click();
  33. setTimeout(function () {
  34. // 移除内存中的临时文件路径和为下载而创建的a标签
  35. URL.revokeObjectURL(downloadURL);
  36. a.remove();
  37. }, 10000);
  38. },
  39. error: function (xhr, textStatus, errorMessage) {
  40. // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码
  41. const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo"));
  42. // 对错误信息进行打印
  43. console.log(errorInfo);
  44. }
  45. });
  46. }

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

  1. /**
  2. *axios方法后台返回流方式下载
  3. */
  4. function btn7() {
  5. debugger;
  6. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  7. const fileName = "Benjamin_Download_Test_File_20221225.pdf";
  8. this.axios.get(url, {responseType: 'blob'}).then(response => {
  9. // 创建a标签
  10. let a = document.createElement("a");
  11. a.download = fileName;
  12. // 创建二进制对象
  13. const blob = new Blob([response.data]);
  14. const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob);
  15. a.href = downloadURL;
  16. // 模拟点击
  17. a.click();
  18. //释放资源并删除创建的a标签
  19. URL.revokeObjectURL(downloadURL);// a.href
  20. document.body.removeChild(a);
  21. }).catch(error => {
  22. console.log(error);
  23. });
  24. }

下载按钮: 

 都可以成功下载:

 2.完整源码

后台简单源码:

  1. @RestController
  2. @RequestMapping("/flower/beetl")
  3. @CrossOrigin
  4. public class BeetlController {
  5. @GetMapping(value = "/downloadFile")
  6. public void downloadFile(HttpServletResponse httpServletResponse) {
  7. File file = new File("C:\\Users\\admin\\Desktop\\download\\Benjamin_Download_Test_File.pdf");
  8. InputStream is = null;
  9. OutputStream os = null;
  10. try {
  11. is = new FileInputStream(file);
  12. os = httpServletResponse.getOutputStream();
  13. httpServletResponse.setContentType("application/octet-stream");
  14. httpServletResponse.setHeader("Content-Disposition", "attachment;fileName=Benjamin_Download_Test_File.pdf");
  15. int len = 0;
  16. byte[] bytes = new byte[1024];
  17. while ((len = is.read(bytes)) != -1) {
  18. os.write(bytes, 0, bytes.length);
  19. os.flush();
  20. }
  21. } catch (FileNotFoundException e) {
  22. e.printStackTrace();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. } finally {
  26. try {
  27. is.close();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. try {
  32. os.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }

 html页面源码:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>7中下载方式</title>
  6. </head>
  7. <body>
  8. <div style="margin-left:60px;margin-top:20px">
  9. <button id="btn1" onclick="btn1()" style="background-color:red" >window.location.href下载</button><br> <br>
  10. <button id="btn2" onclick="btn2()" style="background-color:orange">window.location下载</button><br> <br>
  11. <button id="btn3" onclick="btn3()" style="background-color:yellow">iframe下载</button><br> <br>
  12. <button id="btn4" onclick="btn4()" style="background-color:green">form表单的形式下载</button><br> <br>
  13. <button id="btn5" onclick="btn5()" style="background-color:cyan">a标签的方式下载</button><br> <br>
  14. <button id="btn6" onclick="btn6()" style="background-color:blue">ajax方式后台返回文件流下载</button><br> <br>
  15. <button id="btn7" onclick="btn7()" style="background-color:purple">axios方法后台返回流方式下载</button><br> <br>
  16. </div>
  17. </body>
  18. <!-- <script th:src="@{js/jquery.min.js}"></script> -->
  19. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  20. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  21. <script>
  22. /**
  23. *window.location.href下载
  24. */
  25. function btn1() {
  26. debugger;
  27. window.location.href = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  28. }
  29. /**
  30. *window.location下载
  31. */
  32. function btn2() {
  33. debugger;
  34. window.location='http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile';
  35. }
  36. /***
  37. *iframe下载
  38. */
  39. function btn3() {
  40. try {
  41. var elementIF = document.createElement("iframe");
  42. elementIF.src = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  43. elementIF.style.display = "none";
  44. document.body.appendChild(elementIF);
  45. }catch(error) {
  46. console.log(error);
  47. }
  48. }
  49. /**
  50. *form表单的形式下载
  51. */
  52. function btn4() {
  53. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  54. var form = $("<form>");
  55. form.attr("style", "display:none");
  56. /**target 属性规定一个名称或一个关键词,指示在何处打开 action URL,
  57. * 即在何处显示提交表单后接收到的响应。
  58. *
  59. *_blank 在新窗口/选项卡中打开。
  60. *_self 在同一框架中打开。(默认)
  61. *_parent 在父框架中打开。
  62. *_top 在整个窗口中打开。
  63. *framename 在指定的 iframe 中打开。
  64. */
  65. form.attr("target", "_self");
  66. form.attr("method", "get");
  67. form.attr("action", url);
  68. $("body").append(form);
  69. // 提交
  70. form.submit();
  71. }
  72. /**
  73. *a标签的方式下载
  74. **/
  75. function btn5() {
  76. const fileName = "Benjamin_Download_Test_File.pdf";
  77. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  78. var a = document.createElement("a");
  79. a.download = fileName;
  80. a.href = url;
  81. // 修复firefox中无法触发click
  82. $("body").append(a)
  83. a.click();
  84. $(a).remove();
  85. }
  86. /**
  87. *
  88. *ajax方式后台返回文件流下载、
  89. *success(data, textStatus, jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。
  90. *
  91. *关键在于dataType和xhrFields的属性指定上,指定对属性才能返回blob文件流,dataType: 'binary',xhrFields: {responseType: 'blob'},
  92. */
  93. function btn6() {
  94. debugger;
  95. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  96. $.ajax({
  97. url: url,
  98. type: 'get',
  99. data: {},
  100. contentType: 'application/json;charset=utf-8',
  101. // 指定服务器返回的类型,因为我们要返回文件流,所以类型为二进制数据
  102. dataType: 'binary',
  103. // 原生XMLHttpRequest 的属性,设置响应类型为blob,接收文件流
  104. xhrFields: {responseType: 'blob'},
  105. success: function(result, status, xhr) {
  106. const fileName = "Benjamin_Download_Test_File_20221225.pdf";
  107. // 可通过XMLHttpRequest对象,获取响应头
  108. console.log(xhr);
  109. // 浏览器兼容 参数Blob类型
  110. const downloadURL = (window.URL || window.webkitURL).createObjectURL(result);
  111. // 创建a标签
  112. var a = document.createElement('a');
  113. // 下载后文件的名字
  114. a.download = fileName;
  115. a.href = downloadURL;
  116. document.body.appendChild(a);
  117. a.click();
  118. setTimeout(function () {
  119. // 移除内存中的临时文件路径和为下载而创建的a标签
  120. URL.revokeObjectURL(downloadURL);
  121. a.remove();
  122. }, 10000);
  123. },
  124. error: function (xhr, textStatus, errorMessage) {
  125. // 从响应头中获取异常信息,如果包含中文的话会乱码因此 后台URLEncoder.encode() + 前台decodeURIComponent() 防止乱码
  126. const errorInfo = decodeURIComponent(xhr.getResponseHeader("errorInfo"));
  127. // 对错误信息进行打印
  128. console.log(errorInfo);
  129. }
  130. });
  131. }
  132. /**
  133. *axios方法后台返回流方式下载
  134. */
  135. function btn7() {
  136. debugger;
  137. const url = "http://127.0.0.1:6767/file/download/service/flower/beetl/downloadFile";
  138. const fileName = "Benjamin_Download_Test_File_20221225.pdf";
  139. this.axios.get(url, {responseType: 'blob'}).then(response => {
  140. // 创建a标签
  141. let a = document.createElement("a");
  142. a.download = fileName;
  143. // 创建二进制对象
  144. const blob = new Blob([response.data]);
  145. const downloadURL = (window.URL || window.webkitURL).createObjectURL(blob);
  146. a.href = downloadURL;
  147. // 模拟点击
  148. a.click();
  149. //释放资源并删除创建的a标签
  150. URL.revokeObjectURL(downloadURL);// a.href
  151. document.body.removeChild(a);
  152. }).catch(error => {
  153. console.log(error);
  154. });
  155. }
  156. </script>
  157. <style>
  158. button{
  159. width:200px;
  160. height:35px;
  161. }
  162. </style>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/63618
推荐阅读
相关标签
  

闽ICP备14008679号