我试图让用户使用以下代码从服务器下载zip文件: 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");
}
}
客户端:
$.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");
}
});
但下载的文件已损坏。大小比它应该大,当尝试在存档管理器中打开文件时,也会显示以下消息: zipinfo:在/ home / tengiz / Downloads / exported-shape-file(1).zip中找不到zipfile目录。 / home / tengiz / Downloads / exported-shape-file(1).zip.zip,找不到/ home / tengiz / Downloads / exported-shape-file(1).zip.ZIP,period。
答案 0 :(得分:0)
我解决了这个问题,结果证明问题出在客户端而不是服务器端。 在客户端,我试图将响应附加到href,但由于响应包含字节代码,因此它丢失了一些重要的字符。你需要做的就是创建一个带有控制器方法链接的标签,这样你就不需要像这样的任何ajax请求了:
var a = document.createElement('a');
a.href = '/url-to/get-shape-file';
document.body.appendChild(a);
a.click();