springboot本地下载

将需要下载的资源放在resiurcs/static/中,然后下载下来

前端代码,使用thymeleaf模板为例index.html放在resources/templates中




  
  
  
  Document
  





后台代码

/**
     * 下载Excel模板
     */
    @ApiOperation(value = "下载物资总清单导入模板", notes = "下载物资总清单导入模板", httpMethod = "POST")
    @RequestMapping(value = "/downloadTemp", produces= MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void  downloadTemp(@RequestParam("fileName")String fileName,HttpServletRequest request, HttpServletResponse response) {
        //定义文件名
//        String fileName = "D1120物资总清单导入模板.xlsx";
        try {
            //获取资源文件
            ClassPathResource classPathResource = new ClassPathResource("static/"+fileName);
            //设置响应类型
            response.setCharacterEncoding("UTF-8");
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            response.setHeader("content-Type", type);
            if(Objects.equals(getBrowser(request), "FF")){//如果是火狐,解决火狐中文名乱码问题
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" +new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
            }else{
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }

            //获取资源文件输入流和httpServletResponse的输出流
            try (InputStream inputStream =classPathResource.getInputStream(); ServletOutputStream servletOutputStream = response.getOutputStream()) {
                //把资源文件的二进制流数据copy到response的输出流中
                IOUtils.copy(inputStream, servletOutputStream);
                //清除flush所有的缓冲区中已设置的响应信息至客户端
                response.flushBuffer();
            } catch (Exception e) {
                //错误日志记录
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            //自定义业务异常
            throw new ProjectException("导出模板失败");
        }

    }

    // 判断浏览器种类的方法
    private String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") >= 0)
                return "IE";
            if (UserAgent.indexOf("firefox") >= 0)
                return "FF";
            if (UserAgent.indexOf("safari") >= 0)
                return "SF";
        }
        return null;
    }

 

你可能感兴趣的:(springboot本地下载)