i’m trying to create a page where users can download some .log file. this is the code :
if(action.equalsIgnoreCase("download")){
String file = (String)request.getParameter("file");
response.setHeader("Content-Disposition",
"attachment;filename="+file+"");
response.setContentType("text/plain");
File down_file = new File("log/"+file);
FileInputStream fileIn = new FileInputStream(down_file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();
return null;
}
where am i doing wrong ?
when i click on the download button it correctly ask me to save the file, but it is always a 0 byte file…
This should do the job:
where
ByteStreams.copycomes from wonderful Google’s Guava library.EDIT:
Also, if you are using Spring MVC 3.1 you can do it in cleaner way (that’s how I do it, turns out to be one-liner ;)):
and in your
servlet.xmladd converter tomvc:message-converters:so that you can return
byte[]from any@Controllermethod annotated with@ResponseBody. Read more here and here.Files.toByteArrayis also from Guava.