使用Freemarker解析ftl转为html页面上传OSS




一、yml配置文件

server:
  port: 80
spring:
  application:
    name: freemarker
  freemarker:
    cache: false #关闭模版缓存
    settings:
      template_update_delay: 0 #模版更新的延迟时间  设置0表示立可检查
    suffix: .ftl  #模版后缀  默认ftlh
    template-loader-path: classpath:/templates/ #模版加载路径  默认值也是classpath:/templates/
    #阿里云 OSS
    #不同的服务器,地址不同
aliyun:
  oss:
    file:
      endpoint: xxx
      keyid: xxx
      keysecret: xxx
      bucketname: xxx

二、OSS配置文件

读取yml配置的OSS相关信息

@ConfigurationProperties(prefix = "aliyun.oss.file")
@Configuration
public class OssConfig{
    @Value("${endpoint}")
    private String endpoint;
    @Value("${keyid}")
    private String keyid;
    @Value("${keysecret}")
    private String keysecret;
    @Value("${bucketname}")
    private String bucketname;

}

三、将OSS对象交给Spring

@Configuration
@DependsOn(value ={"ossConfig"})
public class OssConfig2 {
    @Bean
    @Scope(value = "prototype")
    public OSS oss(){
        return new OSSClientBuilder().build(OssConfig.ENDPOINT,OssConfig.KEY_ID,OssConfig.KEY_SECRET);
    }
}

四、解析ftl文件转换为html文件并上传OSS

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OSS ossClient;
    @Autowired
    private Configuration configuration;
    @Autowired
    private ResourceLoader loader;
    /**
     *
     * @param id 生成的html名称
     * @param map 将map中的参数在 步骤1中<获取要解析的模板.ftl>文件解析
     * @param module 上传到OSS的模块名称
     * @param suffix 前台发送过来的文件后缀
     * @return
     * @throws Exception
     */
    public String uploadFileToOss(String id, HashMap<String, Object> map, String module, String suffix) throws Exception {
        //步骤1:获取要freemarker的ftl解析模板
        Template template = configuration.getTemplate("获取要解析的模板.ftl");
        //步骤2:创建一个字符流
        StringWriter writer = new StringWriter();
        //步骤3:将要解析到 (获取要解析的模板.ftl) 中的参数存入map
        //步骤4:解析
        //将map中的数据解析到步骤1指定的.ftl文件中,并把ftl的前端代码存入StringWriter中,StringWriter中存的是一行一行的前端代码
        template.process(map, writer);
        //步骤5:获取到当前类路径下的路径,是为了存放后面生成的html文件
        org.springframework.core.io.Resource resourcePath = loader.getResource("classpath:templates");
        String htmlAbsolutePath = resourcePath.getFile().getAbsolutePath();
        //步骤6:查看这个路径是否存在,不存在就创建一个
        File fileDoc = new File(htmlAbsolutePath);
        //如果文件夹不存在
        if (!fileDoc.exists()) {
            //创建文件夹
            fileDoc.mkdirs();
        }
        //步骤8:存放步骤7指定的文件路径,并生成html文件
        File outFile = new File(htmlAbsolutePath + "\\" + id + "." + suffix);
        //步骤9:创建一个缓冲流
        BufferedWriter output = new BufferedWriter(new FileWriter(outFile));
        //步骤10:将步骤4中的StringWriter写入到步骤8指定的html文件中
        output.write(writer.toString());
        output.flush();
        output.close();
        //步骤10:将html存入oss做准备,如果不需要上传OSS,上面的步骤已经生成了html文件
        //构建日期路径
        String folder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //文件路径:id.扩展名
        String fileName = htmlAbsolutePath + "\\" + id + "." + suffix;
        if(!ossClient.doesBucketExist(OssConfig.BUCKET_NAME)){
            //创建bucket
            ossClient.createBucket(OssConfig.BUCKET_NAME);
            //设置oss实例的访问权限:公共读
            ossClient.setBucketAcl(OssConfig.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        //文件名:id.扩展名
        fileName = id + fileName.substring(fileName.lastIndexOf("."));
        //文件根路径
        String key = module + "/" + folder + "/" + fileName;
        //文件上传至阿里云
        ossClient.putObject(OssConfig.BUCKET_NAME, key, new FileInputStream(htmlAbsolutePath + "/" + fileName));
        // 关闭OSSClient。
        ossClient.shutdown();
        //将生成的本地html文件删除
        new File(htmlAbsolutePath + "/" + fileName).delete();
        //阿里云文件绝对路径
        return "https://" + OssConfig.BUCKET_NAME + "." + OssConfig.ENDPOINT + "/" + key;
    }
}

五、简化

public String upload1(String id, HashMap<String, Object> map, String module, String suffix) throws Exception {
        Template template = configuration.getTemplate("获取要解析的模板.ftl");
        org.springframework.core.io.Resource resourcePath = loader.getResource("classpath:templates");
        String htmlAbsolutePath = resourcePath.getFile().getAbsolutePath();
        File fileDoc = new File(htmlAbsolutePath);
        if (!fileDoc.exists()) {
            fileDoc.mkdirs();
        }
        FileWriter writer = new FileWriter(htmlAbsolutePath + "\\" + id + "." + suffix);
        //将map中的数据解析到步骤1指定的.ftl文件中,并把ftl的前端代码写入writer自定义html中
        template.process(map, writer);
        //步骤10:将html存入oss做准备,如果不需要上传OSS,上面的步骤已经生成了html文件
        //构建日期路径
        String folder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //文件路径:id.扩展名
        String fileName = htmlAbsolutePath + "/" + id + "." + suffix;
        if (!ossClient.doesBucketExist(OssConfig.BUCKET_NAME)) {
            //创建bucket
            ossClient.createBucket(OssConfig.BUCKET_NAME);
            //设置oss实例的访问权限:公共读
            ossClient.setBucketAcl(OssConfig.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        //文件名:id.扩展名
        fileName = id + fileName.substring(fileName.lastIndexOf("."));
        //文件根路径
        String key = module + "/" + folder + "/" + fileName;
        //文件上传至阿里云
        ossClient.putObject(OssConfig.BUCKET_NAME, key, new FileInputStream(htmlAbsolutePath + "/" + fileName));
        // 关闭OSSClient。
//        ossClient.shutdown();
        //将生成的本地html文件删除
        String path = htmlAbsolutePath + "\\" + fileName;
        new File(path).delete();
        //阿里云文件绝对路径
        return "https://" + OssConfig.BUCKET_NAME + "." + OssConfig.ENDPOINT + "/" + key;
    }

总结

如果对你有帮助点个赞叭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值