layui+java文件下载(从服务器下载到本地)

html:
在table的操作栏增加下载按钮,{{d.supervisorfileUpid}}的作用是取js中d的属性,d应该是本行数据,不用改,herf指向controller中的方法,这里带过去主键id,download后面是文件名,js中初始化表格就行

<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    <a href="/supervisorfileUp/download?supervisorfileUpid={{ d.supervisorfileUpid}}" download="{{ d.supervisorfileUpname}}"class="layui-btn layui-btn-danger layui-btn-xs" >下载</a>
script>

在这里插入图片描述

java后端
这块代码很多地方用过,从其他模块搬的,有的名字没改,不过都是一眼就看懂的东西就不改了

 @ResponseBody
   @RequestMapping("/download")
    public void downfile(HttpServletRequest request,HttpServletResponse response) throws Exception{
       // String downloadPath="D:/download";
        Long fileID = Long.valueOf(request.getParameter("supervisorfileUpid"));
        SupervisorfileUp supervisorfileUpService = this.supervisorfileUpService.getById(fileID);

        String projectfileFilename= supervisorfileUpService.getSupervisorfileUpname();
        /*获取文件的存放路径*/
        String fileSavePath = supervisorfileUpService.getSupervisorfileUpurl();
        String filePath=fileSavePath+projectfileFilename;
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            //return ResponseData.error("File not found!");
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        boolean isOnLine=true;
        response.reset(); // 非常重要
       String  fileName= URLEncoder.encode(f.getName(),"UTF-8");

        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + fileName);
          
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();

        //return  null;
    }

你可能感兴趣的:(tomcat,java,服务器)