随手笔记(十九)——— 服务器下载文件到本地Word和PDF格式,文件名乱码修正

    @GetMapping("/downloadAFile/{id}")
    @ResponseBody
    public void downloadAFile(@PathVariable("id") Integer id,HttpServletRequest request , HttpServletResponse response) {
        BufferedInputStream bis=null;
        OutputStream os=null;
        try {
            FilesDO ilesDO = ilesService.get(id);
            String filePath = apiProperties.getFilePath()+ilesDO.getFilePath();
            String fileName = ilesDO.getFileName();
            String ext=fileName.substring(fileName.lastIndexOf(".")+1);
            response.reset();
            response.setCharacterEncoding("utf-8");
            if(ext=="docx") {
                response.setContentType("application/msword"); // word格式
            }else if(ext=="pdf") {
                response.setContentType("application/pdf"); // word格式
            }

            response.setCharacterEncoding("utf-8");
            // 针对IE或者以IE为内核的浏览器:
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
            filePath = java.net.URLDecoder.decode(filePath,"utf-8");
            File file=new File(filePath);
            response.addHeader("Content-Length", "" + file.length()); //file.length() 就是pdf的大小
            bis=new BufferedInputStream(new FileInputStream(file));
            byte[] b=new byte[bis.available()+1000];
            int i=0;
            os = response.getOutputStream();   //直接下载导出
            while((i=bis.read(b))!=-1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

后端下载文件接口代码

var prefix = "/kill/cell"
$().ready(function() {
    validateRule();
    loadMainFiles();
});
function loadMainFiles() {
    var id = $("#id").val();
    console.log("id+",id);
    $.ajax({
        cache : true,
        type : "POST",
        url:prefix + "/checkTheInformationMain/"+id,
        success:function (data) {
            for (var i=0;i<data.length;i++){
                // var html = '<a href="'+data[i]['tFilePath']+'" download="'+data[i].tFileName+'">'+data[i].tFileName+'</a><br>';
                var html = '<a download="'+data[i].tFileName+'" onclick="downloadAFile('+data[i].tFileId+')">'+data[i].tFileName+'</a><br>';
                $("#mainContract").append(html);
            }
        }
    });
}

function downloadAFile(id){
    console.log(id);
    window.location.href= prefix+"/downloadAFile/"+id;
}

前端js调用部分

<div class="form-group">
    <label class="col-sm-3 control-label">文件:</label>
         <div class="col-sm-8" id="mainContract">

          </div>
</div>

html页面部分

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值