1.a标签下载
通常在咱们写项目的时候会遇到上传下载什么的,在上传完文件后会把文件的路径保存到数据库里以便下载,如果想不通过后台直接下载的话,可以把文件路径给a标签的属性href
<a href="/user/test/xxxx.txt">点击下载</a>
但是有个情况,比如txt,png,jpg等这些浏览器支持直接打开的文件是不会执行下载任务的,而是会直接打开文件,这个时候就需要给a标签添加一个属性“download”;
<a href="/user/test/xxxx.txt" download="文件名.txt">点击下载</a>
这里download也可以不写任何信息,会自动使用默认文件名。在这里说明一些IE好像不支持,只能通过后台代码做。
2.ajax请求下载。直接ajax请求下载,后台方法执行完后但前台没有下载框,不能下载。
可以通过提交假form的方式进行下载
var form = $("<form></form>").attr("action", url).attr("method", "post");
form.append($("<input></input>").attr("type","hidden").attr("name","").attr("value", ""));
form.appendTo('body').submit().remove();
后台excel导出
public static void exportExcel(HttpServletResponse response,String filename,String[] titles,List<Object[]> list){
String excelName =null;
try {
excelName = new String(filename.getBytes("GB2312"),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1");
sheet.setDefaultRowHeightInPoints(20);//行高
HSSFRow header = sheet.createRow(0);//第0行
HSSFCellStyle style = wb.createCellStyle();
//style.setFillBackgroundColor(HSSFColor.AQUA.index);//背景色
//style.setFillPattern(HSSFCellStyle.BIG_SPOTS);//指定填充模式(HSSFCellStyle.SOLID_FOREGROUND)
style.setAlignment(CellStyle.ALIGN_LEFT);//对齐方式
HSSFCell cell = null;
for (int i = 0; i < titles.length; i++) {
cell = header.createCell(i);
cell.setCellValue(titles[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 20 * 200); //设置列宽
}
for (int i = 0; i < list.size(); ++i) {
HSSFRow row = sheet.createRow(i + 1);
Object [] str = list.get(i);
for (int k = 0; k < str.length; k++) {
if(str[k] != null){
row.createCell(k).setCellValue(str[k].toString());
}else{
row.createCell(k).setCellValue("");
}
}
}
try {
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}