controller层一个action控制多个excel文件下载if语句如何实现
假设有两个excel文件需要下载,可以在controller层的action方法中使用if语句实现多个文件下载的逻辑,示例代码如下:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName1 = "file1.xlsx";
String fileName2 = "file2.xlsx";
String filePath1 = "/path/to/file1.xlsx";
String filePath2 = "/path/to/file2.xlsx";
if (StringUtils.isNotBlank(filePath1) && StringUtils.isNotBlank(fileName1)) {
File file1 = new File(filePath1);
if (file1.exists()) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName1, "UTF-8"));
try (OutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file1)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
}
}
}
if (StringUtils.isNotBlank(filePath2) && StringUtils.isNotBlank(fileName2)) {
File file2 = new File(filePath2);
if (file2.exists()) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName2, "UTF-8"));
try (OutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file2)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
}
}
}
}
在上述代码中,首先定义了两个excel文件的文件名和文件路径,然后使用if语句判断文件是否存在,并根据文件存在与否来设置response的属性和输出流的内容。如果只有一个文件需要下载,可以直接去掉一个if语句
原文地址: https://www.cveoy.top/t/topic/ftG8 著作权归作者所有。请勿转载和采集!