목차
접기
728x90
반응형
String filePath = "filePath";
String fileName = file1 + ".txt";
String fileNameOrg = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
try{
request.setCharacterEncoding("UTF-8");
fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
File file = new File(filePath, fileName);
if(file.isFile()){
int bytes = (int)file.length();
String header = request.getHeader("User-Agent");
if (header.contains("MSIE") || header.contains("Trident")) {
fileNameOrg = URLEncoder.encode(fileNameOrg,"UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-Disposition", "attachment;filename=" + fileNameOrg + ";");
} else {
fileNameOrg = new String(fileNameOrg.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameOrg + "\"");
}
response.setContentType( "application/download; UTF-8" );
response.setContentLength(bytes);
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Transfer-Encoding", "binary;");
response.setHeader("Pragma", "no-cache;");
response.setHeader("Expires", "-1;");
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
byte[] readByte = new byte[4096];
try{
while((bytes = fin.read(readByte)) > 0){
outs.write(readByte, 0, bytes);
outs.flush();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
outs.close();
fin.close();
}
} else {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("파일이 존재하지 않습니다.");
}
}catch(Exception e){
e.printStackTrace();
}
728x90
반응형
LIST
'Java' 카테고리의 다른 글
POI 엑셀 라이브러리 style 적용 Tip !! (0) | 2022.01.15 |
---|---|
외부 API 호출하는 방법 제일 기초(외부 API 호출) (0) | 2022.01.06 |
[ Spring Boot ] JSP 파일 연동하는 방법 (0) | 2021.09.12 |
[ Spring Boot ] controller에서 @Controller 어노테이션이 제대로 작동하지 않을 때 보아야할 것. (0) | 2021.09.12 |
[ Spring Boot ] 맥북에 lombok 설치하는 방법 (0) | 2021.09.12 |