@GetMapping("/downloadAFile/{id}")
@ResponseBody
public void downloadAFile(@PathVariable("id") Integer id,HttpServletRequest request , HttpServletResponse response) {
BufferedInputStream bis=null;
OutputStream os=null;
try {
FilesDO ilesDO = ilesService.get(id);
String filePath = apiProperties.getFilePath()+ilesDO.getFilePath();
String fileName = ilesDO.getFileName();
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
response.reset();
response.setCharacterEncoding("utf-8");
if(ext=="docx") {
response.setContentType("application/msword"); // word格式
}else if(ext=="pdf") {
response.setContentType("application/pdf"); // word格式
}
response.setCharacterEncoding("utf-8");
// 针对IE或者以IE为内核的浏览器:
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
filePath = java.net.URLDecoder.decode(filePath,"utf-8");
File file=new File(filePath);
response.addHeader("Content-Length", "" + file.length()); //file.length() 就是pdf的大小
bis=new BufferedInputStream(new FileInputStream(file));
byte[] b=new byte[bis.available()+1000];
int i=0;
os = response.getOutputStream(); //直接下载导出
while((i=bis.read(b))!=-1) {
os.write(b, 0, i);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
后端下载文件接口代码
var prefix = "/kill/cell"
$().ready(function() {
validateRule();
loadMainFiles();
});
function loadMainFiles() {
var id = $("#id").val();
console.log("id+",id);
$.ajax({
cache : true,
type : "POST",
url:prefix + "/checkTheInformationMain/"+id,
success:function (data) {
for (var i=0;i<data.length;i++){
// var html = '<a href="'+data[i]['tFilePath']+'" download="'+data[i].tFileName+'">'+data[i].tFileName+'</a><br>';
var html = '<a download="'+data[i].tFileName+'" onclick="downloadAFile('+data[i].tFileId+')">'+data[i].tFileName+'</a><br>';
$("#mainContract").append(html);
}
}
});
}
function downloadAFile(id){
console.log(id);
window.location.href= prefix+"/downloadAFile/"+id;
}
前端js调用部分
<div class="form-group">
<label class="col-sm-3 control-label">文件:</label>
<div class="col-sm-8" id="mainContract">
</div>
</div>
html页面部分