I am trying to download a file in browser using java. The problem is i am not getting any error in code . but the file is not getting download in the browser. I have reffrenced this site : http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-file.
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
String filePat="pat of the file";
File downloadFile = new File(filePath);
System.out.println("downloadFile path: "+ filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
System.out.println("buffer: "+ buffer.length);
int bytesRead = -1;
// write bytes read from the input stream into the output stream
int counter=0;
while ((bytesRead = inputStream.read(buffer))!=-1 ) {
counter++;
System.out.println("counter: "+ counter+ "bytesRead:"+bytesRead);
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();