vue-axios+springboot实现文件流下载

发布于:2025-02-11 ⋅ 阅读:(29) ⋅ 点赞:(0)

前端vue代码:

<template>
  <div class="app-container documentation-container">
    <div>
      <el-button type="primary" @click="downloadFile('test.xlsx')">下载test.xlsx</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Documentation',
  data() {
    return {
    }
  },
  methods: {
    downloadFile(fileName) {
      axios.get('http://localhost:8081/t/downloadFile/' + fileName, {
        responseType: 'blob'
      })
        .then(function (response) {
          // 处理成功情况
          console.log("res:", response);
          if (response.headers['content-Disposition'] || response.headers['content-type'] == 'application/octet-stream') {
            console.log(11);
            let data = response.data;
            console.log('data', data);
            let blob = new Blob([data], {type: 'application/octet-stream'});
            let href = window.URL.createObjectURL(blob);
            let aElement = document.createElement('a');
            aElement.setAttribute('download', fileName);
            aElement.href = href;
            document.body.appendChild(aElement);
            aElement.click();
            document.body.removeChild(aElement);
            window.URL.revokeObjectURL(href); // 释放blob对象
          }
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
        });
    },
  }
}
</script>

后端代码:

@RestController
@RequestMapping("/t")
public class TestController {

    @CrossOrigin
    @RequestMapping("/downloadFile/{fileName}")
    public void downloadFile(HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException {
        String filePath = "excel/" + fileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
            if (!file.exists()) {
                file.createNewFile();
            }
        }

        //        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString());
        response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到