I'm trying to let user download a zip file from server using this code : SERVER:
@RequestMapping(value = "/get-shape-file", method = RequestMethod.GET)
public void getFile( HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedReader rd = new BufferedReader (new FileReader("/shape/lastlyExportedFileName"));
String fileName = rd.readLine().trim();
rd.close();
try {
OutputStream myOut = null;
FileInputStream fileInputStream = null;
File downzip = new File("/shape/" + fileName);
response.setContentType("TEXT/HTML");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentLength((int) downzip.length());
System.out.println("length " + (int) downzip.length());
//READ DATA FROM FILE
byte[] dataRead = new byte[(int) downzip.length()];
fileInputStream = new FileInputStream(downzip);
fileInputStream.read(dataRead, 0, (int) downzip.length());
//WRITE DATA TO OUTFILE
myOut = response.getOutputStream();
myOut.write(dataRead);
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException ex) {
logger.error("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writing file to output stream");
}
}
Client:
$.ajax({
url: 'url-to-the-method/get-shape-file',
type: 'GET',
success: function(shape) {
console.log(shape);
var a = document.createElement('a');
a.href = 'data:attachment/zip,' + shape;
a.target = '_blank';
a.download = 'exported-shape-file.zip';
document.body.appendChild(a);
a.click();
},
error: function(data) {
Message.error("Could not download shapefile");
}
});
But downloaded file is corrupted. Size is larger than it should be, also when trying to open the file in archive manager this message is shown: zipinfo: cannot find zipfile directory in one of /home/tengiz/Downloads/exported-shape-file (1).zip or /home/tengiz/Downloads/exported-shape-file (1).zip.zip, and cannot find /home/tengiz/Downloads/exported-shape-file (1).zip.ZIP, period.