springboot 프로젝트 에서 서버 파일 압축 zip 형식 다운로드 기능
1. pom. xml 에 FileUtils 와 IOUtils 도구 류 의존 도 를 추가 합 니 다.
commons-io
commons-io
2.2
2. 서버 쪽 에 임시 zip 형식 파일 만 들 기
3. 서버 의 모든 파일 을 새 임시 zip 압축 파일 에 입력
4. zip 파일 을 로 컬 에 다운로드
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
Sbcpolicylabel sbcpolicylabel = sbCommonService.findDowInfoByPolicy(policyNo);
ArrayList iconNameList = new ArrayList();//
String zipName = UUID.randomUUID().toString()+".zip";
String outFilePath = request.getSession().getServletContext().getRealPath("/")+"upload";
File fileZip = new File(outFilePath+zipName);
if("filecomplaintflag".equals(flag)){
try {
if ((sbcpolicylabel.getFilecomplaint() != null || !"".equals(sbcpolicylabel.getFilecomplaint()) || !"null".equals(sbcpolicylabel.getFilecomplaint()))) {
String filecomplaintpath = sbcpolicylabel.getFilecomplaint();
List fileList = FileUtil.getFiles(filecomplaintpath);
FileOutputStream outStream = new FileOutputStream(fileZip);
ZipOutputStream toClient = new ZipOutputStream(outStream);
IOtools.zipFile(fileList,toClient);
toClient.close();
outStream.close();
IOtools.downloadFile(fileZip,response,true);
return null;
//
/**
for (int i = 0; i < fileList.size(); i++) {
String curpath = fileList.get(i).getPath();//
iconNameList.add(curpath.substring(curpath.lastIndexOf("\\") + 1));//
String fileName = new String(filecomplaintpath.getBytes("UTF-8"),"iso8859-1");
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity []>(FileUtils.readFileToByteArray(new File(filecomplaintpath)),
headers, HttpStatus.OK);
}
**/
}
}catch(Exception e){
log.info(" , !");
e.printStackTrace();
}
IOtools 도구 클래스
public class IOtools {
/**
*
*/
public static void zipFile(List files, ZipOutputStream outputStream) throws IOException, ServletException {
try {
int size = files.size();
//
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);
final int MAX_BYTE = 10 * 1024 * 1024; // 10M
long streamTotal = 0; //
int streamNum = 0; //
int leaveByte = 0; //
byte[] inOutbyte; // byte
streamTotal = bInStream.available(); // available
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); //
leaveByte = (int) streamTotal % MAX_BYTE; // ,
if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// , byte
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); //
}
}
//
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); //
inStream.close();
}
} else {
throw new ServletException(" !");
}
} catch (IOException e) {
throw e;
}
}
public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
try {
// 。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if(isDelete)
{
file.delete(); //
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
폴 더 아래 파일 과 디 렉 터 리 를 재 귀적 으로 옮 겨 다 니 는 방법
public static ArrayList getFiles(String path) throws Exception {
// fileList
ArrayList fileList = new ArrayList();
File file = new File(path);
if(file.isDirectory()){
File []files = file.listFiles();
for(File fileIndex:files){
// ,
if(fileIndex.isDirectory()){
getFiles(fileIndex.getPath());
}else {
// ,
fileList.add(fileIndex);
}
}
}
return fileList;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.