ajax请求后端导出excel乱码文件出错

目的:主要是实现一个前端选择某一个目录,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();
        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值