一、Controller
/**
* 下载执行完成的文件
*
* @return
*/
@RequestMapping("/downloadResultFile")
public void downloadResultFile(String filename, HttpServletResponse resp){
if(filename.contains("param")){
filename = filename.substring(0, filename.lastIndexOf("param"));
}
service.downloadResultFile(filename,resp);
}
二、ServiceImpl
/**
* 下载任务完成的生成文件
*
* @param path
*
*/
public void downloadResultFile(String filename, HttpServletResponse resp) {
String paramPath = ConfigUtil.getProperty(CONFIG_FILE_INPUT_OUTPUT_LOCATION,System.getProperty("java.io.tmpdir"));
List<File> files = new ArrayList<>();
String[] fileName = new File(paramPath).list((dir,name)-> name.startsWith(filename));
try {
for(String name:fileName){
files.add(new File(paramPath+ "/" + name));
}
if(files.size()==1){
// 单个文件下载
InputStream inStream = null;
BufferedOutputStream os = null;
inStream = new FileInputStream(files.get(0));
byte[] buffer = new byte[1024];
int byteread;
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(files.get(0).getName(), "UTF-8"));
resp.setContentType("application/octet-stream");
// 读取返回文件
os = new BufferedOutputStream(resp.getOutputStream());
while ((byteread = inStream.read(buffer)) != -1) {
os.write(buffer, 0, byteread);
}
inStream.close();
os.flush();
os.close();
}else if(files.size()>1){
resp.setContentType("APPLICATION/OCTET-STREAM");
resp.setHeader("Content-Disposition","attachment; filename="+ filename+".zip");
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
FileUtil.zipFile(files, "", zos);
zos.flush();
zos.close();
}else{
resp.reset();
try {
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件不存在", "UTF-8"));
resp.setContentType("application/octet-stream");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
三、FileUtil
/**
* 将多个文件打包成zip文件
*
* @param subs
* @param baseName
* @param zos
* @throws IOException
*/
public static void zipFile(List<File> subs, String baseName, ZipOutputStream zos) throws IOException {
for (File f : subs) {
zos.putNextEntry(new ZipEntry(baseName + f.getName()));
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
}