간단한 JSP 페이지가 있는데보기 및 내보내기 버튼이 2 개 있습니다. 보기 버튼을 클릭하면 DB에서 데이터를 가져오고 복사본을 세션에 보관하고 데이터가 포함 된 레이블에 HTML 코드를 작성합니다. 나중에 사용자가 내보내기를 클릭하면 서버의 Excel 데이터 파일 (세션의 데이터 포함)을 생성하여 클라이언트 측에 다운로드하려고합니다.AJAX로 JSP로 파일 다운로드
Excel 파일을 서버 측에서 만들었습니다. 클라이언트 측에서 AJAX 요청을 사용하여 서버에서 Excel 파일을 다운로드하고 있습니다.
JSP 코드 : 여기
try{
String filepath=ExportToExcel(session.getAttribute("InvestmentDetails"));
//Setting file to download
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment; filename=\"SIPInvestment_531.xls\"");
response.setStatus(200);
InputStream in = null;
ServletOutputStream outs = response.getOutputStream();
try {
File filetodownload=new File(filepath);
response.setContentLength(Integer.parseInt(String.valueOf(filetodownload.length())));
in = new BufferedInputStream(new FileInputStream(filetodownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close();
}
outs.flush();
outs.close();
}
catch(Exception ex){
str=ex.getMessage();
}
는 자바 스크립트입니다 :
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
xmlhttp.open("POST","/SIP/rptClientInvestmentDetails.jsp?requesttype=export",false);
xmlhttp.send();
요청은 JSP 페이지에 도달한다. 예외없이 출력 응답 스트림에 기록합니다. 그러나 다운로드는 브라우저에서 팝업되지 않습니다. 무엇이 문제 일 수 있습니까?
를 사용하지 않고 자바 함수에 JSP에서 컨트롤을 전송합니다 같이 location.href = 사용 "자바 클래스 함수 이름을 제공"할 수 있다고 생각 JSP에 포함 된 부적절한 Java 코드로 응답에 다시 쓰기를 시도하기 때문에 이미 응답 쓰기가 시작 되었습니까? –