前言,这里用的是springboot+vue前后端分离
首先我们把需要下载的文件放入到resource目录下面
@RestController
@RequestMapping("/excelDown")
@Slf4j
public class InvestExcelDownController {
//下载模板
@PostMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
System.out.println("进入了下载模板");
String filePath = "你的文件路径"; // 文件路径
File file = new File(filePath);
if (file.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
try (InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
接下来是后端的编写,下面是常用到的相对路径下载
System.out.println("进入了下载模板");
File file = ResourceUtils.getFile("classpath:ExcelDownTemplate/文件名");// 文件路径
<div slot="footer" class="dialog-footer">
<el-link type="info" style="font-size:12px" @click="importTemplate">下载对应模板</el-link>
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
触发点击事件,路径对应上即可下载
importTemplate(){ console.log("下载开始") this.download('excelDown/download', { ...this.queryParams }, `模板${new Date().getTime()}.xlsx`) }
效果如下,点击下载,就会自动去下载设置好的文件