当前位置:   article > 正文

使用Axios从前端上传文件并且下载后端返回的文件

使用Axios从前端上传文件并且下载后端返回的文件

前端代码:

  1. function uploadAndDownload(){
  2. showLoading();
  3. const fileInput = document.querySelector('#uploadFile');
  4. const file = fileInput.files[0];
  5. const formData = new FormData()
  6. formData.append('file', file)
  7. return new Promise((resolve, reject) => {
  8. axios({
  9. url: '/generateJrxml',
  10. method: 'post',
  11. data: formData,
  12. responseType: 'blob',
  13. headers: {
  14. 'Content-Type': 'multipart/form-data'
  15. }
  16. }).then(res => {
  17. const { data, headers } = res
  18. const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
  19. const blob = new Blob([data], {type: headers['content-type']})
  20. let dom = document.createElement('a')
  21. let url = window.URL.createObjectURL(blob)
  22. dom.href = url
  23. dom.download = decodeURI(fileName)
  24. dom.style.display = 'none'
  25. document.body.appendChild(dom)
  26. dom.click()
  27. dom.parentNode.removeChild(dom)
  28. window.URL.revokeObjectURL(url)
  29. })
  30. .catch(e => {
  31. console.log(e)
  32. reject(e)
  33. })
  34. })
  35. }

后端代码 

  1. @PostMapping(value = "/generateJrxml", produces = "application/json")
  2. ResponseEntity<InputStreamResource> generateJrxmlFromExcel(@RequestParam("file") MultipartFile uploadFile){
  3. try {
  4. String fileContent = jasperJrxmlGenerateService.generateJrxmlFile(uploadFile)
  5. byte[] bytes = fileContent.getBytes("UTF-8")
  6. ByteArrayInputStream bais = new ByteArrayInputStream(bytes)
  7. HttpHeaders headers = new HttpHeaders()
  8. headers.add("Content-Disposition", "attachment;filename=" + uploadFile.getOriginalFilename().takeBefore('.') + ".jrxml")
  9. return ResponseEntity.ok()
  10. .headers(headers)
  11. .contentType(MediaType.parseMediaType("application/octet-stream"))
  12. .body(new InputStreamResource(bais))
  13. }catch(Exception e){
  14. HttpHeaders headers = new HttpHeaders()
  15. return ResponseEntity.internalServerError().headers(headers)
  16. }
  17. }

完整的前端代码如下: 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" href="jasper.css">
  7. <title>Jasper Helper</title>
  8. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"/>
  9. <!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>-->
  10. <!-- <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>-->
  11. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  12. <script type="text/javascript">
  13. function clickUpload(){
  14. document.getElementById("uploadFile").click();
  15. }
  16. function showFileName(files){
  17. const fileName = files[0].name;
  18. document.getElementById("file-name").innerHTML = fileName;
  19. }
  20. function showLoading(){
  21. var file = document.getElementById("uploadFile").value;
  22. if(file == ''){
  23. console.error("please upload file!");
  24. alertFileMissing();
  25. }else{
  26. document.querySelector('#load-icon').style.display = "inline-block";
  27. console.log('loading')
  28. }
  29. }
  30. function closeLoading(){
  31. document.querySelector('#load-icon').style.display = "none";
  32. console.log('end loading')
  33. }
  34. function closeAlert(){
  35. document.querySelector('#alert').style.display = "none";
  36. }
  37. function alertFileMissing(){
  38. document.querySelector('#alert').style.display = "inline-block";
  39. }
  40. function closeAlertSuccess(){
  41. document.querySelector('#alertSuccess').style.display = "none";
  42. }
  43. function alertSuccess(){
  44. document.querySelector('#alertSuccess').style.display = "inline-block";
  45. }
  46. function closeAlertFailure(){
  47. document.querySelector('#alertFailure').style.display = "none";
  48. }
  49. function alertFailure(){
  50. document.querySelector('#alertFailure').style.display = "inline-block";
  51. }
  52. function uploadAndDownload(){
  53. showLoading();
  54. const fileInput = document.querySelector('#uploadFile');
  55. const file = fileInput.files[0];
  56. const formData = new FormData()
  57. formData.append('file', file)
  58. return new Promise((resolve, reject) => {
  59. axios({
  60. url: '/generateJrxml',
  61. method: 'post',
  62. data: formData,
  63. responseType: 'blob',
  64. headers: {
  65. 'Content-Type': 'multipart/form-data'
  66. }
  67. }).then(res => {
  68. closeLoading()
  69. const { data, headers } = res
  70. const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
  71. const blob = new Blob([data], {type: headers['content-type']})
  72. let dom = document.createElement('a')
  73. let url = window.URL.createObjectURL(blob)
  74. dom.href = url
  75. dom.download = decodeURI(fileName)
  76. dom.style.display = 'none'
  77. document.body.appendChild(dom)
  78. dom.click()
  79. dom.parentNode.removeChild(dom)
  80. window.URL.revokeObjectURL(url)
  81. alertSuccess()
  82. })
  83. .catch(e => {
  84. closeLoading()
  85. console.log(e)
  86. alertFailure()
  87. reject(e)
  88. })
  89. })
  90. }
  91. </script>
  92. </head>
  93. <body class="jasper-wrap">
  94. <div class="container overflow-hidden text-center">
  95. <br/><br/><br/><br/><br/><br/><br/><br/>
  96. <h3>Jasper Helper</h3>
  97. <br/>
  98. <!-- <form id="upload-form" action="/generateJrxml" method="post" enctype="multipart/form-data">-->
  99. <form id="upload-form">
  100. <input type="file" id="uploadFile" name="file" accept=".xlsx,.xls" style="display:none;" onchange="showFileName(this.files)" required>
  101. <button type="button" class="btn btn-outline-primary" onclick="clickUpload()">
  102. <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="currentColor" class="bi bi-file-earmark-arrow-up-fill" viewBox="0 0 16 16">
  103. <path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.707 4L10 .293A1 1 0 0 0 9.293 0M9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1M6.354 9.854a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 8.707V12.5a.5.5 0 0 1-1 0V8.707z"/>
  104. </svg>
  105. UPLOAD
  106. </button>
  107. <br/>
  108. <div id="file-name"></div>
  109. <br/>
  110. <button type="button" class="btn btn-success" onclick="uploadAndDownload()">
  111. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle" viewBox="0 0 16 16">
  112. <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/>
  113. <path d="m10.97 4.97-.02.022-3.473 4.425-2.093-2.094a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05"/>
  114. </svg>
  115. GENERATE
  116. </button>
  117. </form>
  118. <div class="container mt-3">
  119. <div class="spinner-border text-info" id="load-icon" style="display:none"></div>
  120. </div>
  121. <div id="alert" class="alert alert-warning" style="display:none">
  122. <a href="#" class="close" data-dismiss="alert" onclick="closeAlert()">
  123. &times;
  124. </a>
  125. <strong>ERROR!</strong>Please upload file!
  126. </div>
  127. <div id="alertFailure" class="alert alert-warning" style="display:none">
  128. <a href="#" class="close" data-dismiss="alert" onclick="closeAlertFailure()">
  129. &times;
  130. </a>
  131. <strong>ERROR!</strong>Failed to generate JRXML file!
  132. </div>
  133. <div id="alertSuccess" class="alert alert-success" style="display:none">
  134. <a href="#" class="close" data-dismiss="alert" onclick="closeAlertSuccess()">&times;</a>
  135. <strong>SUCCESS!</strong> JRXML file generated successfully!
  136. </div>
  137. </div>
  138. </body>
  139. </html>

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/548519
推荐阅读
相关标签
  

闽ICP备14008679号