아약스 호출을 통해 호출 된 아래 코드를 사용하여 Excel 파일을 만듭니다. 다운로드 버튼을 클릭하면 Excel 파일이 루트 위치에서 생성됩니다. 하지만 사용자가 저장/저장하라는 메시지를 파일로 볼 수 없습니다. 엑셀의 내용이 나오는 브라우저의 응답 탭을 볼 수 있습니다. 하지만 다른 이름으로 저장 대화 상자 옵션이 필요합니다. 이 문제를 해결할 수있는 코드 아래의 수정 사항은 무엇입니까? 다음은 Excel 파일을 통해 서블릿 다운로드
final Date date = new Date();
final String generateDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
final String filename = form_name+"-extraction-"+generateDate.toString()+".xls";
final FileOutputStream fileOutputStream = new FileOutputStream(filename);
workbook.write(fileOutputStream);
downloadFile(filename, response);
다운로드 파일 방법 :
private void downloadFile(final String fileName, final SlingHttpServletResponse response){
try {
final File f = new File(fileName);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "inline; filename="+fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
final int size = 1024;
try {
response.setContentLength(fin.available());
final byte[] buffer = new byte[size];
ServletOutputStream os = null;
os = response.getOutputStream();
int length = 0;
while ((length = fin.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
fin.close();
os.flush();
os.close();
} catch (final IOException e) {
e.printStackTrace();
}
}catch (final Exception ex){
LOGGER.error("ERROR IS ::: {}",ex.getMessage());
}
또한 Ajax 호출에 문제가 있습니다. http://stackoverflow.com/questions/4814877/how-to-download-file-via-ajax-with-http-post-i-e-some-info-in-body. 숨겨진 필드를 사용하여 전화를 받으십시오. –
@VivekDhiman 실제로 파일을 디스크 [FileSaver.js] (https://github.com/eligrey/FileSaver.js)에 저장할 수있는 자바 스크립트 라이브러리가 있습니다. 또는 큰 파일로 작업 할 경우 [StreamSaver.js] (https://github.com/jimmywarting/StreamSaver.js)를 사용할 수 있습니다. – Onur