记录ClassPathResource获取不到文件

一、前言

前两天写自助端单机版系统,获取resource——templete文件夹中的文件。在idea中启动项目是可以获取到的,但是打成Jar包后通过java -jar xxx.jar启动就无法获取到文件

Resource resource = new ClassPathResource("/" + pdfName);
File file = resource.getFile();

二、解决办法

Resource resource = new ClassPathResource("/" + pdfName);
InputStream is = resource.getInputStream();

三、完整代码

@ResponseBody
@RequestMapping(value = "/getFile", method = RequestMethod.POST)
public Object printPdf(@RequestBody ApiParam dto) {
    JSONObject jsonObject = new JSONObject();
    BASE64Encoder base64 = new BASE64Encoder();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        String pdfName = "temporary/个人参保证明.pdf";
        Resource resource = new ClassPathResource("/" + pdfName);
        InputStream is = resource.getInputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(result.toByteArray());
        //PDF文件转换为JPG图片
        JSONArray fileJpg = FileUtils.bytePdfImage(byteArrayInputStream, "jpg");
        //生成的图片信息返回
        jsonObject.put("imgUrl", fileJpg);
        //PDF文件流信息返回
        jsonObject.put("pdfUrl", base64.encode(result.toByteArray()));
    } catch (Exception e) {
        return ApiResult.error();
    }
    return ApiResult.success(jsonObject);
}

你可能感兴趣的:(SpringBoot,Java,java,开发语言)