java下载resource目录的文件

	/**
     * 根据工具名称下载工具
     *
     * @param toolName
     *          工具名
     * @param response
     * @return com.vteam.sme.api.entity.RespEntity
     * @author marke.huang
     * @date 2018/10/15 0015 下午 1:12
     */
    @ApiOperation("根据工具名称下载工具")
    @GetMapping(value = "/getToolByToolName/{toolName}")
    public RespEntity getToolByToolName(@PathVariable("toolName") String toolName, HttpServletResponse response) throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("/templates/tool/" + toolName);
        // 文件类型
        String fileType = toolName.substring(toolName.lastIndexOf(".") + 1);
        // 设置Response参数
        this.setResponse(toolName, fileType, response);
        // 输出文件
        OutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);

        return RespEntity.ok();
    }
	/**
     * 设置Response参数
     *
     * @param showName
     *          下载名
     * @param fileType
     *          文件类型
     * @param response
     * @return void
     * @author marke.huang
     * @date 2018/10/15 0015 下午 1:09
     */
    private void setResponse(String showName, String fileType, HttpServletResponse response)
            throws UnsupportedEncodingException {
        if (fileType.equalsIgnoreCase(GlobalConstants.FileFormat.DOC) || fileType.equalsIgnoreCase(GlobalConstants.FileFormat.DOCX)) {
            response.setContentType("application/msword");
        } else if (fileType.equalsIgnoreCase(GlobalConstants.FileFormat.PDF)) {
            response.setContentType("application/pdf");
        } else if (fileType.equalsIgnoreCase(GlobalConstants.FileFormat.TIF)) {
            response.setContentType("image/tiff");
        } else if (fileType.equalsIgnoreCase(GlobalConstants.FileFormat.XLS) || fileType.equalsIgnoreCase(GlobalConstants.FileFormat.XLSX)) {
            response.setContentType("application/vnd.ms-excel");
        } else if (fileType.equalsIgnoreCase(GlobalConstants.FileFormat.PFX)) {
            response.setContentType("pfx");
        } else {
            response.setContentType("application/x-download");
        }
        String codeFileName = URLEncoder.encode(showName, GlobalConstants.Character.UTF_8);
        codeFileName = codeFileName.replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + codeFileName);
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
    }

猜你喜欢

转载自blog.csdn.net/marke_huang/article/details/83058389