官方文档
1、文件下载api
HTML5+ API Referencehttps://www.html5plus.org/doc/zh_cn/downloader.html
2、文件下载api
HTML5+ API Referencehttps://www.html5plus.org/doc/zh_cn/io.html#plus.io.resolveLocalFileSystemURL
HTML5+ API Referencehttps://www.html5plus.org/doc/zh_cn/runtime.html#plus.runtime.openFile
3、说明
手机app触发下载功能,下载文件到用户手机上。然后自动弹出打开文件的推荐打开软件(如果手机未安装软件,则提示下载打开该文件的软件后续才能打开文件)
4、代码
手机端:
<body style="background-color: #FFFFFF;">
<div class="mui-content" style="padding-bottom: 100px;" >
<div style="width: 100%;height: 50px;line-height: 50px;font-weight: bold;font-size: 20px;margin-bottom: 0px;text-align: left;">
<form class="mui-input-group">
<div class="mui-input-row" style="height: 44px;" >
<label>开始时间</label>
<input type="text" data-options='{}' class="date-btn" readonly="readonly" id="startdate" placeholder="请选择开始时间" autocomplete="off">
</div>
<div class="mui-input-row" style="height: 44px;">
<label>结束时间</label>
<input type="text" data-options='{}' class="date-btn" readonly="readonly" id="enddate" placeholder="请选择结束时间" autocomplete="off" >
</div>
<button type="button" class="mui-btn mui-btn-green" style="width: 50%;padding: 15px 0px;font-size: 18px;" id="exportBtn" data-id="">导出</button>
</div>
</form>
</div>
</div>
//导出数据 exportBtn
var exportBtn = document.getElementById("exportBtn");
exportBtn.addEventListener("tap", function(){
var startdate = document.getElementById("startdate").value;//开始时间
var enddate = document.getElementById("enddate").value;//结束时间
//alert("开始时间:" + startdate + ",结束时间:" + enddate );
if (!startdate || startdate.length == 0 || !enddate || enddate.length == 0){
plus.nativeUI.alert("请选择开始时间和结束时间", function(){}, "系统提示", "确定");
return;
}
getAdminOrderListExport(startdate, enddate);
});
//导出工单信息 getAdminOrderListExport
function getAdminOrderListExport(startdate, enddate ){
var postData = {
startdate: startdate,
enddate: enddate
}
var postDataStr = "";
postDataStr += "startdate=" + startdate;
postDataStr += "&enddate=" + enddate;
var url = AppPath + "/faultOrder/adminOrderListExport";
var wt = plus.nativeUI.showWaiting('数据正在导出,请勿关闭');
var dtask = plus.downloader.createDownload(url,{
method:"POST",
data: postDataStr
},function(d,status){
if(status == 200){
plus.nativeUI.closeWaiting();
var path = d.filename;
plus.io.resolveLocalFileSystemURL( path, function(entry){
plus.nativeUI.alert("导出成功。文件路径: " + entry.fullPath, function(){
plus.runtime.openFile( entry.fullPath);
}, "系统提示", "确定");
}, function(){
plus.nativeUI.alert("导出文件失败!", function(){}, "系统提示", "确定");
});
}else{
plus.nativeUI.alert('导出失败,错误码:'+status, function(){}, "系统提示", "确定");
}
});
dtask.start();
}
后端:
/**
* 导出工单信息
* @param sign
* @return
*/
// @ResponseBody
@RequestMapping(value = "/adminOrderListExport" , method = RequestMethod.POST)
public ResponseEntity<byte[]> getAdminOrderListExport(
@RequestParam("startdate") String startdate,
@RequestParam("enddate") String enddate,
HttpServletRequest request
){
try {
if (StringUtils.isNotEmpty(startdate)
&& StringUtils.isNotEmpty(enddate)) {
//请查询一个月内的数据
// String searchDate = decryptStartdate.substring(0 , 7);
// if (!decryptEnddate.startsWith(searchDate)){
// return JsonUtils.JsonError("请查询一个月内的数据!");
// }
//查询参数
Map<String , Object> paramsMap = new HashMap<>();
paramsMap.put("startdate" , decryptStartdate);
paramsMap.put("enddate" , decryptEnddate);
List<Map<String , Object>> listMap = faultOrderService.getAdminOrderList(paramsMap);
// logger.info("获取工单数据导出: " + mapper.writeValueAsString(listMap));
File exportFile = adminOrderListExportHandle(listMap , request);
// ok表示http请求中状态码200
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
// 内容长度
builder.contentLength(exportFile.length());
// application/octet-stream 二进制数据流(最常见的文件下载)
// builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
// xls 文件下载格式
builder.contentType(MediaType.parseMediaType("application/vnd.ms-excel"));
// 使用URLEncoding.decode对文件名进行解码
String filename = URLEncoder.encode(exportFile.getName(), "UTF-8");
// 根据浏览器类型,决定处理方式
builder.header("Content-Disposition", "attachment; filename=" + filename);
return builder.body(FileUtils.readFileToByteArray(exportFile));
}
} catch (Exception e){
e.printStackTrace();
logger.error("导出工单数据异常," + e.getMessage());
// return JsonUtils.JsonException("获取数据出现异常");
}
return null;
}
//导出数据
public File adminOrderListExportHandle(List<Map<String, Object>> list, HttpServletRequest request){
File toFile = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
StringBuffer sb = new StringBuffer("");
sb.append("运维工单统计表").append("-").append(sdf.format(new Date())).append(".xls");
String filename = new String(sb.toString().getBytes("iso-8859-1"));
String shellName = sb.toString();
// String filePath = "/static/upload/" + shellName;
// toFile = new File(request.getRealPath(filePath));
toFile = new File(getFaultFilePath()+ shellName);
// logger.info("filepath ; " + getFaultFilePath());
// toFile = new File(shellName);
String titles[] = { "工单编号", "姓名", "手机号", "处室", "房间号", "报修类型" , "故障等级" , "故障描述", "工单时间", "处理人", "到场时间", "完成时间"};
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(shellName);
sheet.autoSizeColumn(1, true);
HSSFCellStyle style = wb.createCellStyle();
HSSFRow row = sheet.createRow(0);
row.setHeightInPoints(20);//目的是想把行高设置成20px
// style.setAlignment();
HSSFCell cell;
for (int i = 0; i < titles.length; i++) {
cell = row.createCell((short) i);
cell.setCellValue(titles[i]);
cell.setCellStyle(style);
}
int totalCount = 0;
for (short i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
Map<String,Object> currentDataMap = list.get(i);
String workOrderId = currentDataMap.get("workOrderId").toString();//工单编号
String username = currentDataMap.get("username").toString();//姓名
String mobile = currentDataMap.get("mobile").toString();//手机号
String departmentName = currentDataMap.get("departmentName").toString();//处室
String roomNumber = currentDataMap.get("roomNumber").toString();//房间号
String repairTypeText = currentDataMap.get("repairTypeText").toString();//报修类型
String faultLevelText = currentDataMap.get("faultLevelText").toString();//故障等级
String faultDesc = currentDataMap.get("faultDesc").toString();//故障描述
String createDate = currentDataMap.get("createDate").toString();//工单时间
String workUserName = currentDataMap.get("workUserName").toString();//处理人
String confirmProcessDate = currentDataMap.get("confirmProcessDate").toString();//到场时间
String confirmRepairedDate = currentDataMap.get("confirmRepairedDate").toString();//完成时间
row.setHeightInPoints(30);//目的是想把行高设置成20px
row.createCell(0).setCellValue(workOrderId);
row.createCell(1).setCellValue(username);
row.createCell(2).setCellValue(mobile);
row.createCell(3).setCellValue(departmentName);
row.createCell(4).setCellValue(roomNumber);
row.createCell(5).setCellValue(repairTypeText);
row.createCell(6).setCellValue(faultLevelText);
row.createCell(7).setCellValue(faultDesc);
row.createCell(8).setCellValue(createDate);
row.createCell(9).setCellValue(workUserName);
row.createCell(10).setCellValue(confirmProcessDate);
row.createCell(11).setCellValue(confirmRepairedDate);
}
// row = sheet.createRow(list.size() + 1);
// row.setHeightInPoints(30);//目的是想把行高设置成20px
// row.createCell(0).setCellValue("采集总量");
// row.createCell(1).setCellValue(""+totalCount);
// 回去输出流
// toFile = new File(sb.toString());
OutputStream os = new FileOutputStream(toFile);
wb.write(os);
// FileUtils.copyFile(toFile , os);
os.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("处理导出文件出错: " + e.getMessage());
}
return toFile;
}
注意事项: 上面后端使用的是 springmvc 实现文件下载功能,跟struts2、原生servlet用法有点区别。
springmvc 另一种导出方式(xls)
Java使用poi导出数据到excel文件(单表或多表导出)https://blog.csdn.net/zgphacker2010/article/details/110499696
JSP实现文件上传和文件下载https://blog.csdn.net/zgphacker2010/article/details/124520408
struts2 下载文件