I am wondering if the following code can be modified to be used with latest version of spring APIs? The following code works fine. However, I wanted to know if servlet APIs can be avoided which i have used in the code below.
public void download (HttpServletRequest request, HttpServletResponse response, @PathVariable String filename, @PathVariable String user) throws IOException{
String param1 = filename;
String param2 = user;
//The following URL will need to be updated with "prod" or "dev" or "test" depending upon the environment
final String FILE_LOCATION = "/mnt/nfs/myfolder/prod/documents/custom_documents/"+param2;
if(param1 == null || param2 == null) {
// The Request Parameters Were Not Present In The Query String. Do Something Or Exception Handling !!
System.out.println("Request Parameter Not Found in first if!");
} else if ("".equals(param1) || "".equals(param2)) {
// The Request Parameters Were Present In The Query String But Has No Value. Do Something Or Exception Handling !!
System.out.println("Request Parameter Not Found in second if!");
} else {
String fileName = (String) param1;
String contentType = getContentType(fileName.split("\\.")[1]);
File file = new File(FILE_LOCATION + "/" +fileName);
response.setContentType(contentType);
response.addHeader("Content-Disposition","attachment; filename=" + fileName);
response.setContentLength((int) file.length());
ServletOutputStream servletOutputStream = response.getOutputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int bytesRead = bufferedInputStream.read();
while (bytesRead != -1) {
servletOutputStream.write(bytesRead);
bytesRead = bufferedInputStream.read();
}
if (servletOutputStream != null) servletOutputStream.close();
if(bufferedInputStream != null) bufferedInputStream.close();
}
}
private String getContentType(String fileType) {
String returnType = null;
for(int i = 0; i < contentTypes.length; i++) {
if(fileType.equals(contentTypes[i][0])) returnType = contentTypes[i][1];
}
return returnType;
}