当前位置:   article > 正文

springboot 中的 文件、短信、邮件、token 工具类_token工具类,包括哪些主要功能

token工具类,包括哪些主要功能

1、文件工具类

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

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

        添加依赖:

  1. <dependency>
  2. <groupId>com.aliyun.oss</groupId>
  3. <artifactId>aliyun-sdk-oss</artifactId>
  4. <version>2.8.3</version>
  5. </dependency>
  1. public class FileUtil extends cn.hutool.core.io.FileUtil {
  2. //阿里云 OSS 对象存储
  3. private static final String END_POINT = "http://oss-cn-beijing.aliyuncs.com"; //北京
  4. private static final String ACCESS_KEY_ID = "你自己的"; //accessKeyId
  5. private static final String ACCESS_KEY_SECRET = "你自己的"; //accessKeySecret
  6. private static final String BUCKET = "springboot-frame"; //bucket
  7. private static final String FILE_DIR = "admin/"; //文件保存基路径
  8. //文件类型
  9. private static final String DOCUMENT = ".doc .docx .pdf .pps .ppt .txt .xls .xlsx";
  10. private static final String MUSIC = ".aac .aif .mpa .mp3 .m4a .ra .ram .wav .wma";
  11. private static final String IMAGE = ".bmp .cdr .dib .dif .eps .gif .iff .jpeg .jpg .mpt .pcd .pcp .png .psd .tga .tif .wmf";
  12. private static final String VIDEO = ".asf .avi .flv .mov .mpe .mpeg .mpg .mp4 .m4v .ogg .ogv .qt .rm .webm .wmv";
  13. /**
  14. * 上传文件
  15. * @param fileBase64 文件的 base64格式
  16. * @param fileName 文件名(带后缀)
  17. * @return
  18. */
  19. public static FileEntity uploadFile(String fileBase64, String fileName) {
  20. //创建阿里云客户端对象
  21. OSSClient ossClient = new OSSClient(END_POINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
  22. FileEntity fileEntity = new FileEntity();
  23. byte[] fileByte = Base64Utils.decodeFromString(fileBase64);
  24. //获取文件后缀
  25. int lastIndexOf = fileName.lastIndexOf(".");
  26. String fileType = fileName.substring(lastIndexOf);
  27. try {
  28. //生成文件名
  29. String fileNewName = generateFileName(fileType);
  30. //将文件从 base64 格式转化成文件,以便获取文件大小等信息
  31. FileOutputStream fileOutputStream = new FileOutputStream(
  32. System.getProperty("java.io.tmpdir") + File.separator + fileNewName);
  33. fileOutputStream.write(fileByte);
  34. fileOutputStream.close();
  35. //文件输出未知为系统临时缓存目录
  36. File file = new File(System.getProperty("java.io.tmpdir") + File.separator + fileNewName);
  37. if (file.exists()) {
  38. ObjectMetadata objectMetadata = new ObjectMetadata();
  39. InputStream inputStream = new ByteArrayInputStream(fileByte);
  40. objectMetadata.setContentLength(inputStream.available());
  41. //上传文件
  42. PutObjectResult putObjectResult = ossClient.putObject(BUCKET,
  43. FILE_DIR + getFileDir(fileType) + fileNewName, inputStream, objectMetadata);
  44. //判断结果,并将文件信息返回
  45. if (StringUtil.isNotEmpty(putObjectResult.getETag())) {
  46. fileEntity.setOriginalName(fileName);
  47. fileEntity.setFileName(fileNewName);
  48. fileEntity.setFileType(getFileType(fileType));
  49. fileEntity.setFileSize(file.length() + "");
  50. fileEntity.setFilePath(getFileUrl(fileNewName));
  51. return fileEntity;
  52. } else {
  53. return null;
  54. }
  55. }
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. }
  59. return null;
  60. }
  61. /**
  62. * 判断文件上传位置(阿里云位置)
  63. * @param type
  64. * @return
  65. */
  66. public static String getFileDir(String type) {
  67. if (DOCUMENT.contains(type)) {
  68. return "documents/";
  69. } else if (MUSIC.contains(type)) {
  70. return "musics/";
  71. } else if (IMAGE.contains(type)) {
  72. return "images/";
  73. } else if (VIDEO.contains(type)) {
  74. return "videos/";
  75. } else {
  76. return "others/";
  77. }
  78. }
  79. /**
  80. * 判断文件类型
  81. * @param type
  82. * @return
  83. */
  84. public static String getFileType(String type) {
  85. if (DOCUMENT.contains(type)) {
  86. return "文档";
  87. } else if (MUSIC.contains(type)) {
  88. return "音频";
  89. } else if (IMAGE.contains(type)) {
  90. return "图片";
  91. } else if (VIDEO.contains(type)) {
  92. return "视频";
  93. } else {
  94. return "其它";
  95. }
  96. }
  97. /**
  98. * 生成文件名
  99. * @param fileType 文件类型
  100. * @return
  101. */
  102. public static String generateFileName(String fileType) {
  103. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
  104. String date = simpleDateFormat.format(new Date());
  105. String fileName = date + fileType;
  106. return fileName;
  107. }
  108. /**
  109. * 根据文件名获取文件路径
  110. * @param fileName
  111. * @return
  112. */
  113. public static String getFileUrl(String fileName) {
  114. OSSClient ossClient = new OSSClient(END_POINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
  115. //链接有效期 9h
  116. Date expiration = new Date(new Date().getTime() + 9 * 60 * 60);
  117. //获取文件后缀
  118. int lastIndexOf = fileName.lastIndexOf(".");
  119. String fileType = fileName.substring(lastIndexOf);
  120. String url = ossClient.generatePresignedUrl(BUCKET,FILE_DIR + getFileDir(fileType),
  121. expiration).toString();
  122. return url;
  123. }
  124. }

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

  1. public static void main(String[] args) {
  2. File file = new File("/Users/xinou/Desktop/photos/pc-one-big.jpeg");
  3. if (file.exists()) {
  4. try {
  5. FileInputStream fileInputStream = new FileInputStream(file.getPath());
  6. byte[] bytes = new byte[fileInputStream.available()];
  7. fileInputStream.read(bytes);
  8. fileInputStream.close();
  9. String s = Base64Utils.encodeToString(bytes);
  10. FileEntity fileEntity = uploadFile(s, file.getName());
  11. System.out.println(fileEntity.getOriginalName() + ", " + fileEntity.getFileName() + ", "
  12. + fileEntity.getFileType() + ", " + fileEntity.getFileSize() + ", "
  13. + fileEntity.getFilePath());
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }

 

 

2、短信工具类

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

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

        添加依赖:

  1. <!--短信验证码-->
  2. <!--阿里云-->
  3. <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
  4. <dependency>
  5. <groupId>com.aliyun</groupId>
  6. <artifactId>aliyun-java-sdk-core</artifactId>
  7. <version>4.1.1</version>
  8. </dependency>
  9. <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-dysmsapi -->
  10. <dependency>
  11. <groupId>com.aliyun</groupId>
  12. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  13. <version>1.1.0</version>
  14. </dependency>
  15. <!--腾讯云-->
  16. <!-- https://mvnrepository.com/artifact/com.github.qcloudsms/qcloudsms -->
  17. <dependency>
  18. <groupId>com.github.qcloudsms</groupId>
  19. <artifactId>qcloudsms</artifactId>
  20. <version>1.0.6</version>
  21. </dependency>
  1. public class ShortMsgUtil {
  2. private static final String ALI_PRODUCT = "你自己的"; //产品名称
  3. private static final String ALI_PRODUCT_URL = "dysmsapig.aliyuncs.com"; //产品域名
  4. private static final String ALI_ACCESS_KEY_ID = "你自己的"; //key id
  5. private static final String ALI_ACCESS_KEY_SECRET = "你自己的"; //key 密钥
  6. private static final String ALI_SIGN_NAME = "人世间子"; //短信签名
  7. private static final String ALI_TEMPLATE_CODE = "你自己的"; //短信模板
  8. private static final Integer TXUN_APP_ID = 你自己的; //应用 app_id
  9. private static final String TXUN_APP_KEY = "你自己的"; //应用 app_key
  10. private static final String TXUN_SIGN_NAME_ID = "人世间子"; //签名 id
  11. private static final Integer TXUN_TEMPLATE_ID = 420791; //模板 id
  12. private static final Integer PRONHUB = 420843;
  13. private static final String TXUN_SMSG_CODE = "86"; //区号
  14. /**
  15. * 短信验证码(阿里云) 假设用户账号是手机号
  16. * @param mobile
  17. * @param code
  18. * @return 0:发送成功;1:发送失败
  19. */
  20. public static Integer sendSMsgCodeALi(String mobile, String code) {
  21. Integer result = 1;
  22. IClientProfile iClientProfile = DefaultProfile.getProfile("cn-hangzhou", ALI_ACCESS_KEY_ID, ALI_ACCESS_KEY_SECRET);
  23. try {
  24. DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", ALI_PRODUCT, ALI_PRODUCT_URL);
  25. IAcsClient iAcsClient = new DefaultAcsClient(iClientProfile);
  26. SendSmsRequest request = new SendSmsRequest();
  27. request.setPhoneNumbers(mobile);
  28. request.setSignName(ALI_SIGN_NAME);
  29. request.setTemplateCode(ALI_TEMPLATE_CODE);
  30. request.setTemplateParam("\"code\":\"" + code + "\"}");
  31. SendSmsResponse response = iAcsClient.getAcsResponse(request);
  32. if (response.getCode() != null && "OK".equals(response.getCode())) {
  33. result = 0;
  34. } else {
  35. result = 1;
  36. }
  37. } catch(ClientException e) {
  38. e.printStackTrace();
  39. }
  40. return result;
  41. }
  42. /**
  43. * 短信验证码(腾讯云) 假设用户账号为手机号
  44. * @param mobile
  45. * @param code
  46. * @return 0:发送成功;1:发送失败
  47. */
  48. public static Integer sendSMsgCodeTXun(String mobile, String[] code) {
  49. Integer result = 1;
  50. try {
  51. SmsSingleSender smsSingleSender = new SmsSingleSender(TXUN_APP_ID, TXUN_APP_KEY);
  52. SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam(TXUN_SMSG_CODE,
  53. mobile, TXUN_TEMPLATE_ID, code, TXUN_SIGN_NAME_ID, "", "");
  54. result = smsSingleSenderResult.result;
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. return result;
  59. }
  60. }

 

3、邮件工具类

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

        添加依赖:

  1. <!--发送邮件-->
  2. <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
  3. <dependency>
  4. <groupId>javax.mail</groupId>
  5. <artifactId>mail</artifactId>
  6. <version>1.4.7</version>
  7. </dependency>
  1. public class EmailUtil {
  2. private static final String FROM = "香格里拉集团"; //发送方昵称;
  3. private static final String FROM_ACCOUNT = "youremail@163.com"; //发送方账号
  4. private static final String GRAN_CODE = "你自己的"; //授权码
  5. private static final String URL = "http://localhost:8081/api/admin/user/activate"; //激活链接地址 激活地址为自己项目中的 api
  6. /**
  7. * 邮件激活 假设用户账号是邮箱
  8. * @param userId
  9. * @param userName
  10. */
  11. public static void sendActivateLik(Integer userId, String userName) {
  12. Session session = getSession();
  13. MimeMessage message = new MimeMessage(session);
  14. try {
  15. String content = "<p>您好!</p>"
  16. + "<p>&nbsp;&nbsp;&nbsp;&nbsp;欢迎加入香格里拉集团,请点击此链接激活账号!</p>"
  17. + "<p>&nbsp;&nbsp;&nbsp;&nbsp;<a target='_BLANK' href='" + URL + "?=" + userId + "'>"
  18. + URL + "?id=" + userId + "</a></p>";
  19. message.setSubject("香格里拉集团 | 账号激活"); //邮件主题
  20. message.setSentDate(new Date());
  21. message.setFrom(new InternetAddress(FROM_ACCOUNT, FROM, "UTF-8"));
  22. message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(userName));
  23. message.setContent(content, "text/html;charset=gb2312");
  24. Transport.send(message);
  25. } catch (MessagingException e) {
  26. e.printStackTrace();
  27. } catch (UnsupportedEncodingException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. /**
  32. * 邮件验证码 假设用户账号是邮箱
  33. * @param userName
  34. * @param code
  35. */
  36. public static void sendEmailCode(String userName, String code) {
  37. Session session = getSession();
  38. MimeMessage message = new MimeMessage(session);
  39. try {
  40. String content = "<p>您好!</p>"
  41. + "<p>&nbsp;&nbsp;&nbsp;&nbsp;欢迎加入香格里拉集团,您的验证码为:</p>"
  42. + "<p>&nbsp;&nbsp;&nbsp;&nbsp;" + code + "</p>";
  43. message.setSubject("香格里拉集团 | 验证码"); //邮件主题
  44. message.setSentDate(new Date());
  45. message.setFrom(new InternetAddress(FROM_ACCOUNT, FROM, "UTF-8"));
  46. message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(userName));
  47. message.setContent(content, "text/html;charset=gb2312");
  48. Transport.send(message);
  49. } catch (MessagingException e) {
  50. e.printStackTrace();
  51. } catch (UnsupportedEncodingException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. /**
  56. * 邮件配置
  57. * @return
  58. */
  59. public static Session getSession() {
  60. Properties properties = new Properties();
  61. properties.setProperty("mail.transport.protocol", "smtp"); //指定发送邮件的邮箱协议
  62. properties.setProperty("mail.smtp.host", "smtp.163.com"); //指定smtp服务器
  63. properties.setProperty("mail.smtp.port", "25"); //端口号:25
  64. properties.setProperty("mail.smtp.auth", "true"); //指定是否需要smtp验证
  65. Session session = Session.getInstance(properties, new Authenticator() {
  66. @Override
  67. protected PasswordAuthentication getPasswordAuthentication() {
  68. return new PasswordAuthentication(FROM_ACCOUNT, GRAN_CODE);
  69. }
  70. });
  71. return session;
  72. }
  73. }

 

4、token 工具类

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

        添加依赖:

  1. <!--JWT token相关-->
  2. <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api 编译环境 -->
  3. <dependency>
  4. <groupId>io.jsonwebtoken</groupId>
  5. <artifactId>jjwt-api</artifactId>
  6. <version>0.10.5</version>
  7. </dependency>
  8. <!--运行环境-->
  9. <dependency>
  10. <groupId>io.jsonwebtoken</groupId>
  11. <artifactId>jjwt-impl</artifactId>
  12. <version>0.10.5</version>
  13. <scope>runtime</scope>
  14. </dependency>
  15. <dependency>
  16. <groupId>io.jsonwebtoken</groupId>
  17. <artifactId>jjwt-jackson</artifactId>
  18. <version>0.10.5</version>
  19. <scope>runtime</scope>
  20. </dependency>
  1. public class TokenUtil {
  2. //token有效时间 两小时
  3. public static final long EXPIRE_TIME = 7200000;
  4. //签名密钥
  5. private static final String TOKEN_SECRET = "你自己的"; //秘钥可在网上在线生成,也可自己写方法生成
  6. //JWT有效
  7. private static final Integer JWT_BE_BOT_OVERDUE_CODE = 1001;
  8. //JWT过期-无效
  9. private static final Integer JWT_BE_OVERDUE_CODE = 1002;
  10. /**
  11. * 生成JWS JWT签名后称为JWS
  12. * @param subject 用户id 即生成的JWS的唯一所有人
  13. * @return
  14. */
  15. public static String createJWS(String subject) {
  16. SecretKeySpec key = new SecretKeySpec(TOKEN_SECRET.getBytes(), "HmacSHA256"); //签名密钥
  17. long createTime = System.currentTimeMillis(); //JWT生成时间
  18. Date createDate = new Date(createTime);
  19. long expireTime = createTime + EXPIRE_TIME; //JWT有效时间
  20. Date expireDate = new Date(expireTime);
  21. JwtBuilder builder = Jwts.builder(); //new 一个JwtBuilder来设置JWT的body
  22. builder.setId(getUUID()) //设置jti(JWT ID):是JWT的唯一标识,主要用来作为一次性token,从而回避重放攻击
  23. .signWith(key) //指定密钥
  24. .setIssuedAt(createDate) //JWT签发时间
  25. .setSubject(subject) //JWT的主体,即所有人,一般为userId等
  26. .setExpiration(expireDate); //失效时间
  27. return builder.compact(); //开始压缩
  28. }
  29. /**
  30. * 验证JWS
  31. * 验证JWT时的签名密钥跟生成时的签名密钥相同,且生成将其存入数据库,
  32. * 所以验证时如果抛出异常,只能是过期
  33. * @param jwsString
  34. * @return 1001:有效;1002:无效-过期
  35. */
  36. public static Integer checkJWS(String jwsString) {
  37. SecretKeySpec key = new SecretKeySpec(TOKEN_SECRET.getBytes(), "HmacSHA256"); //签名密钥
  38. try {
  39. Jwts.parser().setSigningKey(key).parseClaimsJws(jwsString);
  40. } catch (JwtException e) {
  41. return JWT_BE_OVERDUE_CODE;
  42. }
  43. return JWT_BE_BOT_OVERDUE_CODE;
  44. }
  45. /**
  46. * 生成唯一标识
  47. * @return
  48. */
  49. private final static String getUUID() {
  50. return UUID.randomUUID().toString().replaceAll("-", "");
  51. }
  52. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/908868
推荐阅读
相关标签
  

闽ICP备14008679号