在js中直接使用window.location.href 或者 window.open打开url 会在浏览器中直接开到文件(文件已经存在,不需要生成)
要实现在浏览器中下载的效果
java代码
public static void downloadFile(Long id){
DisposalUser disposalUser=DisposalUser.findById(id);
String url=disposalUser.attachment_file.substring(1, disposalUser.attachment_file.length());
String name=disposalUser.attachment_file.substring(disposalUser.attachment_file.lastIndexOf("/")+1, disposalUser.attachment_file.length());
String[] type=name.split("\\.");
File ff=new File(url);
try {
response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(type[0], "UTF-8")+"."+type[1]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
renderBinary(ff);
}
js代码
$(".download-btn").die().live("click", function() {
var attachment_file=$(this).attr("data-attachment-file");
if(attachment_file==""){
alert("文件不存在!");
return;
}
var id=$(this).attr("data-id");
window.location.href="/dispose/downloadFile?id="+id;
// window.open("/dispose/downloadFile?id="+id)
});
另外一种 导出excel文件
在服务器上生成文件,然后下载到本地
public static void exportAllBlackList(Integer time,@Required @Min(1) Long ti, String query, @DateWithTime String st,
@DateWithTime String et, @Min(1) Integer ps, @Min(1) Integer p, String sb,Integer so,Integer status,String ch,String fname
,String weibotype,String weiboname){
if(time!=null&&time!=-1&&time!=0){
JSONObject range = util.DateUtil.timeRanges(time);
st = range.getString("st");
et = range.getString("et");
}
if(sb==null){
sb = "real_time";
}
if(so==null){
so = -1;
}
String path = "public/check/";
// 创建素材保存目录
File toSave = new File(path);
if (!toSave.exists()) {
toSave.mkdirs();
}
List<Map> result=new ArrayList<Map>();
Groups group=Groups.findById(ti);
String taskName=group.groupName;
String fileName = path + sdf.format(new Date())+taskName.replace("#", "") + "-"+fname+".xls";
HSSFWorkbook wb = new HSSFWorkbook();
result=models.Account.getBlackDocList(query, st, et, ti, p, ps, sb, so,status,false);
ForExcelWB(wb,result,weibotype,weiboname);
try {
FileOutputStream fout = new FileOutputStream(fileName);
wb.write(fout);
fout.flush();
fout.close();
fileName = "/" + fileName; // 修正下载路径
Operate.saveOperate(5, "导出全部的黑名单文章列表-["+ti+"]-"+fileName,getIp());
renderJSON(ResultInfo.success(fileName, ""));
} catch (Exception e) {
e.printStackTrace();
Logger.error(e.getMessage(),e);
renderJSON(ResultInfo.error("导出失败"));
}
}
js代码
export_all(ti,time,st,et,so,sb,"0,1,2",5,weibotype,weixintype,weiboname,weixinname,function(data){
$("body").removeClass("fcyshow");
if(data.result=="success"){
window.location.href=data.info.substring(0,data.info.lastIndexOf("/")+1)+encodeURIComponent(data.info.substring(data.info.lastIndexOf("/")+1,data.info.length));
}else{
alert(data.msg);
}
});