Springboot+vue实现文件的下载

后端Java代码

package cn.com.techfly.lzpid.system.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/fileDownload")
public class FileDownloadController {
    private static final String PDF_FILE_PATH = "E:/file.pdf"; //文件的路径

    @GetMapping(value = "/download",
            produces = "application/json")
    public ResponseEntity<Resource> downloadFile() throws IOException {
        // 创建文件路径
        Path filePath = Paths.get(PDF_FILE_PATH);
        // 检查文件是否存在
        if (!Files.exists(filePath)) {
            throw new IOException("文件不存在: " + filePath);
        }
        // 读取文件内容
        Resource resource = new FileSystemResource(filePath);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + resource.getFilename());
        headers.add("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 创建响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}

前端vue代码

<template>
  <div>
    <button @click="download">下载文件</button>
  </div>
</template>
<script setup>
import axios from 'axios';

const download = () => {
  axios.get("fileDownload/download", {
    responseType: 'blob'  // 告诉 axios 期望服务器响应的数据类型
  })
      .then((response) => {
        if (response.status == 200) {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'file.pdf');
          document.body.appendChild(link);
          link.click();
          // 下载完成后移除 a 标签和释放 URL 对象
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        }
      })
      .catch((error) => {
        console.error(error);
      });
}
</script>
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端代码(使用Vue3和Element Plus): ``` <template> <div> <el-table :data="tableData" stripe> <el-table-column prop="id" label="ID"></el-table-column> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> </el-table> <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next" :total="total"> </el-pagination> </div> </template> <script> import { ref } from 'vue'; import { getTableData } from '@/api/example'; export default { setup() { const currentPage = ref(1); const pageSize = ref(10); const total = ref(0); const tableData = ref([]); async function getData() { const params = { currentPage: currentPage.value, pageSize: pageSize.value, }; const res = await getTableData(params); if (res.code === 200) { tableData.value = res.data.list; total.value = res.data.total; } } function handleCurrentChange(page) { currentPage.value = page; getData(); } getData(); return { currentPage, pageSize, total, tableData, handleCurrentChange, }; }, }; </script> ``` 后端代码(使用Spring Boot 2): ``` @GetMapping("/tableData") public CommonResult<PageResult<TableData>> getTableData(@RequestParam(required = false, defaultValue = "1") Integer currentPage, @RequestParam(required = false, defaultValue = "10") Integer pageSize) { PageResult<TableData> pageResult = tableDataService.getTableData(currentPage, pageSize); return CommonResult.success(pageResult); } ``` 其中,`TableData`为实体类,`PageResult`为分页结果类。`tableDataService`为对应的Service类,用于查询数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值