在springboot下打包文件夾並導出zip包代碼如下
@ApiOperation(value="導出接口")
@RequestMapping(value="/export",method = RequestMethod.GET)
public void export(HttpServletRequest request, HttpServletResponse response) throws IOException{
OutputStream out = response.getOutputStream();
try {
response.setCharacterEncoding("UTF-8");
String path = searchService.export();
File file = new File(path);
byte[] data = getStream(path);
// 壓縮包名稱
String downloadName = file.getName();
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
if(!file.delete()){
file.deleteOnExit();
}
} catch (IOException ex) {
ex.printStackTrace();
}finally {
try{
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private byte[] getStream(String filePath) {
byte[] buffer = null;
File file = new File(filePath);
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis!=null)
fis.close();
if(bos!=null)
bos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return buffer;
}