java后端代码

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/api/files")
public class FileDownloadController {

    // 文件存储路径(根据实际情况修改)
    private static final String FILE_DIRECTORY = "/path/to/your/files/";

    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) {
        File file = new File(FILE_DIRECTORY + fileName);

        if (file.exists()) {
            try (InputStream inputStream = new FileInputStream(file)) {
                // 设置响应头
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
                response.setContentLength((int) file.length());

                // 将文件流写入响应输出流
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                response.getOutputStream().flush();
            } catch (IOException e) {
                throw new RuntimeException("文件下载失败", e);
            }
        } else {
            throw new RuntimeException("文件不存在");
        }
    }
}

vue前端使用axios

<template>
  <div>
    <button @click="downloadFile('example.pdf')">下载文件</button>
  </div>
</template>

<script setup>
import axios from 'axios';

const downloadFile = async (fileName) => {
  try {
    // 调用后端接口
    const response = await axios.get(`/api/files/download/${fileName}`, {
      responseType: 'blob', // 重要:指定响应类型为二进制流
    });

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName); // 设置下载文件名
    document.body.appendChild(link);
    link.click();

    // 释放资源
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('文件下载失败', error);
  }
};

vue前端使用naiveui request封装download方法

export function download({
                             url,
                             data,
                         }: HttpOption) {
    return request({
        url: url,
        data: data,
        method: "POST",
        responseType: 'blob'
    })
}

调用dowanlod方法

function pcapDownload(data: any) {
  let fileName = filename + '.' + suffix;
  download({
    url: `/download/${fileName}`,
    data: null,
  }).then(((res:any) => {
    const { data, headers } = res;
    const blob = new Blob([data], { type: headers['content-type'] });
    const dom = document.createElement('a')
    const downUrl = window.URL.createObjectURL(blob)
    dom.href = downUrl
    dom.download = decodeURIComponent(fileName)
    dom.style.display = 'none'
    document.body.appendChild(dom)
    dom.click();
    //dom.parentNode.removeChild(dom);
    window.URL.revokeObjectURL(downUrl);
  }));
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐