目的:主要是实现一个前端选择某一个目录,js读取目录下所有文件,并上传到后端进行处理,处理完成之后把统计信息导出excel。
第一版:前端请求。结果是:能导出,但是文件数据乱码。网上一通搜索,处理结果要么没效果,要么后端收不到请求。搞了一天,快下班了找到另一种请求方式,见下文。
$.ajax({
url: '/damage/uploadimgList',
type: 'post',
async: false, // 设置为同步执行
processData : false, // 禁止去处理发送的数据,对data参数进行序列化处理时须设置
contentType : false, // 禁止去设置Content-Type请求头
data: data,
// responseType: "arraybuffer",
success: function (res) {
const blob = new Blob([res], {type:"application/vnd.ms-excel"});
if(blob.size < 1) {
alert('导出失败,导出的内容为空!');
return
}
if(window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, 'test.xls')
} else {
const aLink = document.createElement('a');
aLink.style.display = 'none';
aLink.href = window.URL.createObjectURL(blob);
aLink.download = 'test.xls';
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
}
}
});
第二版:改成axios
选择目录
<input type="file" id="selectFiles" onchange="dealSelectFiles()" webkitdirectory multiple>
读取目录下文件,转list,传到后台。
function dealSelectFiles(){
var selectFiles = document.getElementById("selectFiles").files;
var data = new FormData();
for (var i = 0; i < selectFiles.length; i++) {
data.append("files", selectFiles[i]); // append方法使用相同键追加元素,最后会被输出为MultipartFile数组
}
axios.post("/damage/uploadimgList", data, {
responseType: 'blob'
}).then( function (res){
var filename = decodeURI(res.headers['content-disposition'].match(/(filename=(.*))/)[2])
var blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
var objectUrl = URL.createObjectURL(blob);
var $a = $("<a>")
$a.attr("href", objectUrl)
$a.attr("download", filename)
$("body").append($a)
$a[0].click(0);
$a.remove()
}).catch(function (res) {
console.log(res)
})
return false;
}
最后也附上后端
@PostMapping("/uploadimgList")
public void uploadimgList(@RequestParam("files") List<MultipartFile> files, HttpServletResponse response) {
// String fileName = System.currentTimeMillis() + "残损统计.xlsx";
try {
List<DamageExcelVO> objects = demoService.uploadimgList(files);
response.setContentType("application/vnd.ms-excel");
String fileName = new String("残损统计.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
response.setCharacterEncoding("utf8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
ServletOutputStream outputStream = response.getOutputStream();
// 导出
EasyExcel.write(outputStream, DamageExcelVO.class).autoCloseStream(Boolean.FALSE).sheet("残损统计").doWrite(objects);
} catch (Exception e) {
e.printStackTrace();
}
}