后端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'
})
.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();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
}
})
.catch((error) => {
console.error(error);
});
}
</script>