springboot 中的 文件、短信、邮件、token 工具类

1、文件工具类

        主要功能为文件上传,结合阿里云 OSS 对象存储。上传文件类型包括文档、音频、视频、图片等,可自定义文件夹,文件未加密。自动生成文件名,文件上传成功后返回原文件名、新文件名、文件大小、文件类型、文件链接等信息。

        注:文件链接存在有效期,可自行设定。

        添加依赖:

        
            com.aliyun.oss
            aliyun-sdk-oss
            2.8.3
        
public class FileUtil extends cn.hutool.core.io.FileUtil {

    //阿里云 OSS 对象存储
    private static final String END_POINT = "http://oss-cn-beijing.aliyuncs.com";   //北京

    private static final String ACCESS_KEY_ID = "你自己的";   //accessKeyId

    private static final String ACCESS_KEY_SECRET = "你自己的";   //accessKeySecret

    private static final String BUCKET = "springboot-frame";   //bucket

    private static final String FILE_DIR = "admin/";   //文件保存基路径

    //文件类型
    private static final String DOCUMENT = ".doc .docx .pdf .pps .ppt .txt .xls .xlsx";
    private static final String MUSIC = ".aac .aif .mpa .mp3 .m4a .ra .ram .wav .wma";
    private static final String IMAGE = ".bmp .cdr .dib .dif .eps .gif .iff .jpeg .jpg .mpt .pcd .pcp .png .psd .tga .tif .wmf";
    private static final String VIDEO = ".asf .avi .flv .mov .mpe .mpeg .mpg .mp4 .m4v .ogg .ogv .qt .rm .webm .wmv";

    /**
     * 上传文件
     * @param fileBase64 文件的 base64格式
     * @param fileName 文件名(带后缀)
     * @return
     */
    public static FileEntity uploadFile(String fileBase64, String fileName) {
        //创建阿里云客户端对象
        OSSClient ossClient = new OSSClient(END_POINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        FileEntity fileEntity = new FileEntity();
        byte[] fileByte = Base64Utils.decodeFromString(fileBase64);
        //获取文件后缀
        int lastIndexOf = fileName.lastIndexOf(".");
        String fileType = fileName.substring(lastIndexOf);
        try {
            //生成文件名
            String fileNewName = generateFileName(fileType);
            //将文件从 base64 格式转化成文件,以便获取文件大小等信息
            FileOutputStream fileOutputStream = new FileOutputStream(
                    System.getProperty("java.io.tmpdir") + File.separator + fileNewName);
            fileOutputStream.write(fileByte);
            fileOutputStream.close();
            //文件输出未知为系统临时缓存目录
            File file = new File(System.getProperty("java.io.tmpdir") + File.separator + fileNewName);
            if (file.exists()) {
                ObjectMetadata objectMetadata = new ObjectMetadata();
                InputStream inputStream = new ByteArrayInputStream(fileByte);
                objectMetadata.setContentLength(inputStream.available());
                //上传文件
                PutObjectResult putObjectResult = ossClient.putObject(BUCKET,
                        FILE_DIR + getFileDir(fileType) + fileNewName, inputStream, objectMetadata);
                //判断结果,并将文件信息返回
                if (StringUtil.isNotEmpty(putObjectResult.getETag())) {
                    fileEntity.setOriginalName(fileName);
                    fileEntity.setFileName(fileNewName);
                    fileEntity.setFileType(getFileType(fileType));
                    fileEntity.setFileSize(file.length() + "");
                    fileEntity.setFilePath(getFileUrl(fileNewName));
                    return fileEntity;
                } else {
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断文件上传位置(阿里云位置)
     * @param type
     * @return
     */
    public static String getFileDir(String type) {
        if (DOCUMENT.contains(type)) {
            return "documents/";
        } else if (MUSIC.contains(type)) {
            return "musics/";
        } else if (IMAGE.contains(type)) {
            return "images/";
        } else if (VIDEO.contains(type)) {
            return "videos/";
        } else {
            return "others/";
        }
    }

    /**
     * 判断文件类型
     * @param type
     * @return
     */
    public static String getFileType(String type) {
        if (DOCUMENT.contains(type)) {
            return "文档";
        } else if (MUSIC.contains(type)) {
            return "音频";
        } else if (IMAGE.contains(type)) {
            return "图片";
        } else if (VIDEO.contains(type)) {
            return "视频";
        } else {
            return "其它";
        }
    }

    /**
     * 生成文件名
     * @param fileType 文件类型
     * @return
     */
    public static String generateFileName(String fileType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = simpleDateFormat.format(new Date());
        String fileName = date + fileType;
        return fileName;
    }

    /**
     * 根据文件名获取文件路径
     * @param fileName
     * @return
     */
    public static String getFileUrl(String fileName) {
        OSSClient ossClient = new OSSClient(END_POINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        //链接有效期 9h
        Date expiration = new Date(new Date().getTime() + 9 * 60 * 60);
        //获取文件后缀
        int lastIndexOf = fileName.lastIndexOf(".");
        String fileType = fileName.substring(lastIndexOf);
        String url = ossClient.generatePresignedUrl(BUCKET,FILE_DIR + getFileDir(fileType),
                expiration).toString();
        return url;
    }

}

        测试:在实际应用中在前端将用户需要上传的文件转化成 base64 格式,然后传到后端进行上传。

public static void main(String[] args) {
        File file = new File("/Users/xinou/Desktop/photos/pc-one-big.jpeg");
        if (file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file.getPath());
                byte[] bytes = new byte[fileInputStream.available()];
                fileInputStream.read(bytes);
                fileInputStream.close();
                String s = Base64Utils.encodeToString(bytes);
                FileEntity fileEntity = uploadFile(s, file.getName());
                System.out.println(fileEntity.getOriginalName() + ", " + fileEntity.getFileName() + ", "
                        + fileEntity.getFileType() + ", " + fileEntity.getFileSize() + ", "
                        + fileEntity.getFilePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

 

2、短信工具类

        主要包括短信验证码部门。结合阿里云和腾讯云。还可有短信群发等功能。

        注:阿里云需要的 code 参数的格式为字符串型,腾讯云为数组型。

        添加依赖:

        
        
        
        
            com.aliyun
            aliyun-java-sdk-core
            4.1.1
        

        
        
            com.aliyun
            aliyun-java-sdk-dysmsapi
            1.1.0
        

        
        
        
            com.github.qcloudsms
            qcloudsms
            1.0.6
        
public class ShortMsgUtil {

    private static final String ALI_PRODUCT = "你自己的";   //产品名称
    private static final String ALI_PRODUCT_URL = "dysmsapig.aliyuncs.com";   //产品域名
    private static final String ALI_ACCESS_KEY_ID = "你自己的";   //key id
    private static final String ALI_ACCESS_KEY_SECRET = "你自己的";   //key 密钥
    private static final String ALI_SIGN_NAME = "人世间子";   //短信签名
    private static final String ALI_TEMPLATE_CODE = "你自己的";   //短信模板
    private static final Integer TXUN_APP_ID = 你自己的;   //应用 app_id
    private static final String TXUN_APP_KEY = "你自己的";   //应用 app_key
    private static final String TXUN_SIGN_NAME_ID = "人世间子";   //签名 id
    private static final Integer TXUN_TEMPLATE_ID = 420791;   //模板 id
    private static final Integer PRONHUB = 420843;
    private static final String TXUN_SMSG_CODE = "86";   //区号

    /**
     * 短信验证码(阿里云) 假设用户账号是手机号
     * @param mobile
     * @param code
     * @return 0:发送成功;1:发送失败
     */
    public static Integer sendSMsgCodeALi(String mobile, String code) {
        Integer result = 1;
        IClientProfile iClientProfile = DefaultProfile.getProfile("cn-hangzhou", ALI_ACCESS_KEY_ID, ALI_ACCESS_KEY_SECRET);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", ALI_PRODUCT, ALI_PRODUCT_URL);
            IAcsClient iAcsClient = new DefaultAcsClient(iClientProfile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            request.setSignName(ALI_SIGN_NAME);
            request.setTemplateCode(ALI_TEMPLATE_CODE);
            request.setTemplateParam("\"code\":\"" + code + "\"}");
            SendSmsResponse response = iAcsClient.getAcsResponse(request);
            if (response.getCode() != null && "OK".equals(response.getCode())) {
                result = 0;
            } else {
                result = 1;
            }
        } catch(ClientException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 短信验证码(腾讯云) 假设用户账号为手机号
     * @param mobile
     * @param code
     * @return 0:发送成功;1:发送失败
     */
    public static Integer sendSMsgCodeTXun(String mobile, String[] code) {
        Integer result = 1;
        try {
            SmsSingleSender smsSingleSender = new SmsSingleSender(TXUN_APP_ID, TXUN_APP_KEY);
            SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam(TXUN_SMSG_CODE,
                    mobile, TXUN_TEMPLATE_ID, code, TXUN_SIGN_NAME_ID, "", "");
            result = smsSingleSenderResult.result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

 

3、邮件工具类

        邮件工具类包括邮箱验证码和邮箱激活链接。结合 163 邮箱。

        添加依赖:

        
        
        
            javax.mail
            mail
            1.4.7
        
public class EmailUtil {

    private static final String FROM = "香格里拉集团";   //发送方昵称;
    private static final String FROM_ACCOUNT = "[email protected]";   //发送方账号
    private static final String GRAN_CODE = "你自己的";   //授权码
    private static final String URL = "http://localhost:8081/api/admin/user/activate";   //激活链接地址 激活地址为自己项目中的 api

    /**
     * 邮件激活 假设用户账号是邮箱
     * @param userId
     * @param userName
     */
    public static void sendActivateLik(Integer userId, String userName) {
        Session session = getSession();
        MimeMessage message = new MimeMessage(session);
        try {
            String content = "

您好!

" + "

    欢迎加入香格里拉集团,请点击此链接激活账号!

" + "

    " + URL + "?id=" + userId + "

"; message.setSubject("香格里拉集团 | 账号激活"); //邮件主题 message.setSentDate(new Date()); message.setFrom(new InternetAddress(FROM_ACCOUNT, FROM, "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(userName)); message.setContent(content, "text/html;charset=gb2312"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 邮件验证码 假设用户账号是邮箱 * @param userName * @param code */ public static void sendEmailCode(String userName, String code) { Session session = getSession(); MimeMessage message = new MimeMessage(session); try { String content = "

您好!

" + "

    欢迎加入香格里拉集团,您的验证码为:

" + "

    " + code + "

"; message.setSubject("香格里拉集团 | 验证码"); //邮件主题 message.setSentDate(new Date()); message.setFrom(new InternetAddress(FROM_ACCOUNT, FROM, "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(userName)); message.setContent(content, "text/html;charset=gb2312"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 邮件配置 * @return */ public static Session getSession() { Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); //指定发送邮件的邮箱协议 properties.setProperty("mail.smtp.host", "smtp.163.com"); //指定smtp服务器 properties.setProperty("mail.smtp.port", "25"); //端口号:25 properties.setProperty("mail.smtp.auth", "true"); //指定是否需要smtp验证 Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(FROM_ACCOUNT, GRAN_CODE); } }); return session; } }

 

4、token 工具类

        token 工具类中包括生成 token 和验证 token 。

        添加依赖:

        
        
        
            io.jsonwebtoken
            jjwt-api
            0.10.5
        

        
        
            io.jsonwebtoken
            jjwt-impl
            0.10.5
            runtime
        

        
            io.jsonwebtoken
            jjwt-jackson
            0.10.5
            runtime
        
public class TokenUtil {

    //token有效时间 两小时
    public static final long EXPIRE_TIME = 7200000;

    //签名密钥
    private static final String TOKEN_SECRET = "你自己的";   //秘钥可在网上在线生成,也可自己写方法生成

    //JWT有效
    private static final Integer JWT_BE_BOT_OVERDUE_CODE = 1001;

    //JWT过期-无效
    private static final Integer JWT_BE_OVERDUE_CODE = 1002;

    /**
     * 生成JWS      JWT签名后称为JWS
     * @param subject 用户id 即生成的JWS的唯一所有人
     * @return
     */
    public static String createJWS(String subject) {

        SecretKeySpec key = new SecretKeySpec(TOKEN_SECRET.getBytes(), "HmacSHA256");   //签名密钥

        long createTime = System.currentTimeMillis();   //JWT生成时间
        Date createDate = new Date(createTime);
        long expireTime = createTime + EXPIRE_TIME;   //JWT有效时间
        Date expireDate = new Date(expireTime);

        JwtBuilder builder = Jwts.builder();   //new 一个JwtBuilder来设置JWT的body

        builder.setId(getUUID())   //设置jti(JWT ID):是JWT的唯一标识,主要用来作为一次性token,从而回避重放攻击
                .signWith(key)   //指定密钥
                .setIssuedAt(createDate)   //JWT签发时间
                .setSubject(subject)   //JWT的主体,即所有人,一般为userId等
                .setExpiration(expireDate);   //失效时间
        return builder.compact();   //开始压缩
    }

    /**
     * 验证JWS
     *      验证JWT时的签名密钥跟生成时的签名密钥相同,且生成将其存入数据库,
     *      所以验证时如果抛出异常,只能是过期
     * @param jwsString
     * @return 1001:有效;1002:无效-过期
     */
    public static Integer checkJWS(String jwsString) {

        SecretKeySpec key = new SecretKeySpec(TOKEN_SECRET.getBytes(), "HmacSHA256");   //签名密钥

        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(jwsString);
        } catch (JwtException e) {
            return JWT_BE_OVERDUE_CODE;
        }
        return JWT_BE_BOT_OVERDUE_CODE;
    }

    /**
     * 生成唯一标识
     * @return
     */
    private final static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

}

 

 

 

你可能感兴趣的:(spring,boot)