阿里云OSS上传下载和短信验证码

(一):首先得在阿里云OSS上开通相关的服务,具体哪里开通及如何操作请参考此链接:
https://help.aliyun.com/document_detail/31883.html?spm=5176.10695662.1996646101.searchclickresult.5ceb3ee82NzMq7&aly_as=WhUj5kPK

或者视频地址请参考此链接:http://cloud.video.taobao.com/play/u/2955313663/p/1/e/6/t/1/218785851580.mp4

(二):阿里云OSS常见问题及介绍参考此链接:
https://yq.aliyun.com/articles/716527?spm=a2c4e.11155472.0.0.2fe35cbed5F3GK

(三):阿里云OSS错误查询及问题解决参考此链接:
https://error-center.aliyun.com/status/product/Oss

你也可以在此来链接地址上提问题:
https://selfservice.console.aliyun.com/ticket/createIndex

(四):基本功能介绍
初始化 创建存储空间 上传文件 跨域访问设置 设置读写权限

1.初始化:

private string accessKeyId = "xxxxxxxxx";                  
private string accessKeySecret = "xxxxxxxxxx"; 
private string endpoint = "oss-cn-beijing.aliyuncs.com";           //OSS对应的区域地址private static OssClient ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);

2.创建存储空间:

ossClient.CreateBucket("myBucket"); //新建一个Bucket

3.设置读写权限:

//CannedAccessControlList有三个属性:Private(私有),PublicRead(公共读),PublicReadWrite(公共读写)
ossClient.SetBucketAcl("myBucket", CannedAccessControlList.PublicRead);  //设置为公共读

4.跨域访问设置:

var req = new SetBucketCorsRequest("myBucket");
var rule = new CORSRule();
//指定允许跨域请求的来源
rule.AddAllowedOrigin("*");
//指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)
rule.AddAllowedMethod("POST");
//控制在OPTIONS预取指令中Access-Control-Request-Headers头中指定的header是否允许。
rule.AddAllowedHeader("*");

req.AddCORSRule(rule);
ossClient.SetBucketCors(req);

(五):代码示例如下

1:上传

在写代码期间首先需要对如下代码有所认识:

OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); 
ossClient.shutdown();

理解:对比输入输出流来理解想当于启动流和最后关闭流,在swagger中try it out 每个方法时都要开流关流,如果开流是所有方法共用的(声明为成员变量)这样一个方法运行完之后流就关了,在执行下一个方法时就不能了(还得在重新开启),所有不要把
OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET); 声明为成员变量

SendFileController

package com.richfit.richfit.controller;

import com.aliyun.oss.model.ObjectMetadata;
import com.richfit.richfit.service.DownFileService;
import com.richfit.richfit.service.SendFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.net.URL;

/**
 * @ClassName SendFileController
 * @Description: 上传文件
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
@Api(value = "上传文件或下载文件")
@RestController
@RequestMapping(value = "/sys/sendfile")
@Slf4j
public class SendFileController {

    @Autowired
    private SendFileService sendFileService;

    @Autowired
    private DownFileService downFileService;

    //本地或者服务器上文件的路径
    //private final String filePath="E:\\picture\\15C1D7875F17BE8808191E8A8B2EA1D6.jpg";

    @ApiOperation(value = "获取OSS图片,文档,网络流URL用于数据库保存",notes = "获取OSS图片,文档,网络流URL用于数据库保存")
    @RequestMapping(value = "/getOSSUrl",method = RequestMethod.GET)
    public URL getOSSUrl(@ApiParam(name = "key",value = "OSS上OSS图片,文档,网络流URL的名称",required = true) @RequestParam(value = "key",required = true) String key,
                             @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true)String bucketName) throws FileNotFoundException {
        return sendFileService.getOSSUrl(key,bucketName);
    }

    @ApiOperation(value = "上传OSS图片或者视频,上传一张图片或者一个视频",notes = "上传OSS图片或者视频,上传一张图片或者一个视频例如 beautyleg/beautyleg3.jpg,会先创建一个beautylegde的文件夹")
    @RequestMapping(value = "/sendosspicture",method = RequestMethod.POST)
    public  boolean putObject(
            @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true) String bucketName,
            @ApiParam(name = "key",value = "OSS上图片或者视频的名称",required = true) @RequestParam(value = "key",required = true) String key,
            @ApiParam(name = "filePath",value = "本地或者服务器上文件的路径",required = true) @RequestParam(value = "filePath",required = true) String filePath) throws FileNotFoundException {
      return  sendFileService.putObject(bucketName,key,filePath);
    }

    @ApiOperation(value = "删除OSS上图片,删除一张图片",notes = "删除OSS上图片,删除一张图片")
    @RequestMapping(value = "/deleteosspicture",method = RequestMethod.DELETE)
    public boolean deleteOssObject(@ApiParam(name = "key",value = "OSS上图片的名称",required = true) @RequestParam(value = "key",required = true) String key,
                                   @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true)String bucketName){
        return sendFileService.deleteOssObject(key,bucketName);
    }

    /**
     * .zip  .hprof  .jpg  .txt .mp4等好多格式上传到OSS上去
     * @param bucketName
     * @param key
     * @param filePath
     * @return
     * @throws FileNotFoundException
     */
    @ApiOperation(value = "上传OSS文档",notes = "上传OSS文档,注意filepath,key格式一样例如 .txt")
    @RequestMapping(value = "/sendossfile",method = RequestMethod.POST)
    public  boolean sendOssFile(
            @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true) String bucketName,
            @ApiParam(name = "key",value = "OSS上文档的名称",required = true) @RequestParam(value = "key",required = true) String key,
            @ApiParam(name = "filePath",value = "本地或者服务器上文件的路径",required = true) @RequestParam(value = "filePath",required = true) String filePath) throws FileNotFoundException {
        return  sendFileService.sendOssFile(bucketName,key,filePath);
    }

    @ApiOperation(value = "上传OSS网络流",notes = "上传OSS网络流")
    @RequestMapping(value = "/sendossstream",method = RequestMethod.POST)
    public  boolean sendossstream(
            @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true) String bucketName,
            @ApiParam(name = "key",value = "OSS上网络流的名称,这个随便写就行例如 lol jk",required = true) @RequestParam(value = "key",required = true) String key,
            @ApiParam(name = "streamPath",value = "链接地址",required = true) @RequestParam(value = "streamPath",required = true) String streamPath) throws FileNotFoundException {
        return  sendFileService.sendossstream(bucketName,key,streamPath);
    }

    /**
     * 可以下载到本地格式为  .zip  .hprof  .jpg  .txt .mp4等好多格式
     * 下载功能现在没问题但是前台报错:org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON:
     * @param objectName
     * @param bucketName
     * @param localFileAddressName
     * @return
     */
    @ApiOperation(value = "下载OSS上已经存在的东西,存到本地文件,",notes = "下载OSS上已经存在的东西,存到idea项目指定文件")
    @RequestMapping(value = "/downossfile",method = RequestMethod.POST)
    public ObjectMetadata downOssFile(@ApiParam(name = "objectName",value = "OSS上已经存在东西名称,例如  tt.jpg",required = true) @RequestParam(value = "objectName",required = true) String objectName,
                                      @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true)String bucketName,
                                      @ApiParam(name = "localFileAddressName",value = "下载新生产文档名称,若是 .zip 结尾则可以下载为压缩包",required = true) @RequestParam(value = "localFileAddressName",required = true)String localFileAddressName){
        return downFileService.downOssFile(objectName ,bucketName,localFileAddressName);
    }
}



SendFileServiceImpl

package com.richfit.richfit.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.richfit.richfit.OSSClientUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @ClassName SendFileServiceImpl
 * @Description: 上传文件
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
@Service
public class SendFileServiceImpl implements SendFileService{


    /**
     * 获取OSS图片,文档,网络流URL
     * 类似于http://tylgd.oss-cn-beijing.aliyuncs.com/beautyleg1.jpg?Expires=1580794877&OSSAccessKeyId=LTAIzSTybwTVdqMn&Signature=YaHze%2Bvh4ZihN5%2Bbrz1lQ0hbtBo%3D
     * @return
     */
    @Override
    public URL getOSSUrl(String key, String bucketName) {
        Date date = new Date(new Date().getTime());
        OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing();
        URL url = ossClientBeiJing.generatePresignedUrl(bucketName, key, date);
        return url;
    }


    /**
     * 上传OSS图片 上传一张图片 或者一个视频(例如 .mp4)
     * @return
     */
    @Override
    public boolean putObject(String bucketName,String key,String filePath) {
        // key指的是 保存在oss上后的路径+文件名
        // filePath 指的是上传的文件路径
        //参数设置
        //关于这个endPoint,可以参考:http://bbs.aliyun.com/read/149100.html?spm=5176.7189909.0.0.YiwiFw
        //可能报:The bucket you are attempting to access must be addressed using the specified endpoint. Please send
        //System.out.println("Error Message: " + oe.getErrorCode()); 提示你endpoint如何写
        //https://blog.csdn.net/torpidcat/article/details/82867093 endpoint错误提示
        //String bucketName = "tylgd";
        //保存在oss上的文件名
        //String key="beautyleg1.jpg";
        //本地或者服务器上文件的路径
        //String filePath="E:\\picture\\15C1D7875F17BE8808191E8A8B2EA1D6.jpg";//本地或者服务器上文件的路径
        boolean flag=false;
        OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing();
        try{
            // 获取指定文件的输入流
            File file = new File(filePath);
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());
            // 上传Object.
            PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content, meta);
            if (file.isFile() && file.exists()) {
                flag = true;
            }
        }catch(OSSException oe){
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            flag=false;
        }finally {
            ossClientBeiJing.shutdown();
            return flag;
        }
    }

    /**
     * 删除OSS上图片 删除一张图片
     * @param key 图片在OSS上的名称
     * @return
     */
    @Override
    public boolean deleteOssObject(String key,String bucketName) {
        OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing();
        boolean b = ossClientBeiJing.doesObjectExist(bucketName, key);
        //如果存在返回的是true b为true
        if (b){
            ObjectListing objectListing = ossClientBeiJing.listObjects(bucketName);
            ossClientBeiJing.deleteObject(bucketName,key);
            ossClientBeiJing.shutdown();
            return true;
        }
        return false;
    }

    /**
     * 上传OSS文档
     * @param filePath bucketName key
     * @return
     */
    @Override
    public boolean sendOssFile(String bucketName,String key,String filePath) {
        boolean flag=false;
        OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing();
        try{
            // 获取指定文件的输入流
            File file = new File(filePath);
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            //ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            //meta.setContentLength(file.length());
            // 上传Object.
            PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content);
            if (file.isFile() && file.exists()) {
                flag = true;
            }
        }catch(OSSException oe){
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            flag=false;
        }finally {
            ossClientBeiJing.shutdown();
            return flag;
        }
    }

    /**
     * 上传OSS网络流
     * @param bucketName
     * @param key
     * @param streamPath
     * @return
     */
    @Override
    public boolean sendossstream(String bucketName, String key, String streamPath) {
        boolean flag=true;
        OSS ossClientBeiJing = OSSClientUtil.getOssClientBeiJing();
        try{
            // 获取指定文件的输入流
            InputStream content = new URL(streamPath).openStream();
            PutObjectResult result = ossClientBeiJing.putObject(bucketName, key, content);
        }catch(OSSException oe){
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
            flag=false;
        }finally {
            ossClientBeiJing.shutdown();
            return flag;
        }
    }

}

OSSClientUtil

其实阿里云OSS自己就有一个OSSUtils 只是自己又写了一个方便自己用

package com.richfit.richfit;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

/**
 * @ClassName OSSClient
 * @Description:  其实阿里云OSS自己就有一个OSSUtils  只是自己又写了一个方便自己用
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
public class OSSClientUtil {
    //http://oss-cn-hangzhou.aliyuncs.com 杭州的
    public static final String ENDPOINTBEIJING = "http://oss-cn-beijing.aliyuncs.com";//北京的接口
    public static final String ACCESSKEYID = "**********";
    public static final String ACCESSKEYSECRET = "*********";

    /**
     * 北京的OSSClient
     * @return
     */
    public static OSS getOssClientBeiJing(){
        OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET);
        return oSSClient;
    }

    /**
     * 杭州的OSSClient
     * @return
     */
   /* public OSSClient getOssClientHangZhou(){
        OSSClient oSSClient = new OSSClient(endpointbeijing,accessKeyId,accessKeySecret);
        return oSSClient;
    }*/
}

2:下载

DownFileController

/**
     * 可以下载到本地格式为  .zip  .hprof  .jpg  .txt .mp4等好多格式
     * 下载功能现在没问题但是前台报错:org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON:
     * @param objectName
     * @param bucketName
     * @param localFileAddressName
     * @return
     */
    @ApiOperation(value = "下载OSS上已经存在的东西,存到本地文件,",notes = "下载OSS上已经存在的东西,存到idea项目指定文件")
    @RequestMapping(value = "/downossfile",method = RequestMethod.POST)
    public ObjectMetadata downOssFile(@ApiParam(name = "objectName",value = "OSS上已经存在东西名称,例如  tt.jpg",required = true) @RequestParam(value = "objectName",required = true) String objectName,
                                      @ApiParam(name = "bucketName",value = "OSS上Bucket名称",required = true) @RequestParam(value = "bucketName",required = true)String bucketName,
                                      @ApiParam(name = "localFileAddressName",value = "下载新生产文档名称,若是 .zip 结尾则可以下载为压缩包",required = true) @RequestParam(value = "localFileAddressName",required = true)String localFileAddressName){
        return downFileService.downOssFile(objectName ,bucketName,localFileAddressName);
    }

DownFileService

ObjectMetadata downOssFile(String objectName, String bucketName, String localFileAddressName);

DownFileServiceImpl

package com.richfit.richfit.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.richfit.richfit.FileTypeUtil;
import com.richfit.richfit.OSSClientUtil;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @ClassName downFileServiceImpl
 * @Description: 下载OSS上已经存在的东西
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
@Service
public class DownFileServiceImpl implements DownFileService {
    /**
     * 下载OSS上已经存在的东西 存到idea项目指定文件
     * @param objectName
     * @param bucketName
     * @return
     */
    @Override
    public ObjectMetadata downOssFile(String objectName, String bucketName,String localFileAddressName) {
        //String localFileAddressName="src/main/resources/files";
        OSS ossClient = null;
        ObjectMetadata object = null;
        try {
            //创建OSSClient实例,用于操作oss空间
            ossClient = OSSClientUtil.getOssClientBeiJing();
            ossClient.setBucketAcl("tylgd", CannedAccessControlList.PublicReadWrite);
            //指定文件保存路径
            //String filePath = localFileAddressName+"/"+System.currentTimeMillis()+".jpg";
            //判断文件目录是否存在,不存在则创建  .zip  .hprof  结尾都可以  System.currentTimeMillis()+ FileTypeUtil.fileType() 子文件
            File file = new File(localFileAddressName,System.currentTimeMillis()+ FileTypeUtil.fileType(objectName));
            boolean newFile = file.createNewFile();
            if (newFile){
                file.setWritable(true);
                object = ossClient.getObject(new GetObjectRequest(bucketName, objectName), file);
                return object;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        //判断保存文件名是否加后缀
            /*if (objectName.contains(".")){
                //指定文件保存名称
                filePath = filePath+"/"+objectName.substring(objectName.lastIndexOf("/")+1);
            }*/

            //获取OSS文件并保存到本地指定路径中,此文件路径一定要存在,若保存目录不存在则报错,若保存文件名已存在则覆盖本地文件
        return object;
    }
}



OSSClientUtil

package com.richfit.richfit;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

/**
 * @ClassName OSSClient
 * @Description:
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
public class OSSClientUtil {
    //http://oss-cn-hangzhou.aliyuncs.com 杭州的
    public static final String ENDPOINTBEIJING = "http://oss-cn-beijing.aliyuncs.com";//北京的接口
    public static final String ACCESSKEYID = "********";
    public static final String ACCESSKEYSECRET = "************";

    /**
     * 北京的OSSClient
     * @return
     */
    public static OSS getOssClientBeiJing(){
        OSS oSSClient = new OSSClientBuilder().build(ENDPOINTBEIJING,ACCESSKEYID,ACCESSKEYSECRET);
        return oSSClient;
    }

    /**
     * 杭州的OSSClient
     * @return
     */
   /* public OSSClient getOssClientHangZhou(){
        OSSClient oSSClient = new OSSClient(endpointbeijing,accessKeyId,accessKeySecret);
        return oSSClient;
    }*/
}

FileTypeUtil

package com.richfit.richfit;

/**
 * @ClassName FileTypeUtil
 * @Description: OSS上类型和本地文件格式一致
 * @Author BruthLi
 * @Date 2020/2/5
 * @Version V1.0
 **/
public class FileTypeUtil {
    public static String fileType(String samefiletypesame){
        int start = samefiletypesame.lastIndexOf(".");
        String substring = samefiletypesame.substring(start, samefiletypesame.length());
        if (".jpg".equalsIgnoreCase(substring)){
          return  substring;
        }else if (".doc".equalsIgnoreCase(substring)){
          return  substring;
        }else if (".docx".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".md".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".hprof".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".mp4".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".txt".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".java".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".class".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".zip".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".rpm".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".xlsx".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".html".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".xlsx".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".properties".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".xml".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".http".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".jar".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".war".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".dat".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".md".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".cmd".equalsIgnoreCase(substring)){
            return  substring;
        }else if (".iml".equalsIgnoreCase(substring)){
            return  substring;
        }
        return "java代码规定没有此种文本格式!";
    }
}


3:发短信

SendSmsController

package com.richfit.richfit.controller;

/**
 * @ClassName SendSms
 * @Description: 阿里云发送短信 SendSms ,  阿里云发送验证码 SendSms
 * @Author BruthLi
 * @Date 2020/2/3
 * @Version V1.0
 **/

import com.richfit.richfit.service.SendSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/
@Api(value = "发送短信或验证码")
@RestController
@RequestMapping(value = "/sys/sendmessagecode")
@Slf4j
public class SendSmsController {

    @Autowired
    private SendSmsService sendSmsService;

    final String phoneNumber = "**************";

    @ApiOperation(value = "查询验证码是否正确",notes = "查询验证码是否正确")
    @RequestMapping(value = "/sendcodeyesorno",method = RequestMethod.GET)
    public Map<String,String> sendCodeYesOrNo(String inputcode){
        Map<String, String> mapReturn = sendSmsMessage(phoneNumber);
        String code = mapReturn.get("code");
        if (code.equalsIgnoreCase(inputcode)){
         return  mapReturn;
        }
        mapReturn.put("code", "验证码:["+inputcode+"]输入不正确,请重新输入!");
        return  mapReturn;
    }


    /**
     * 发送短信或验证码
     * @param phoneNumber 电话号码
     * @return HttpServletRequest
     */
    @ApiOperation(value = "发送短信或验证码",notes = "发送短信或验证码")
    @RequestMapping(value = "/sendcode",method = RequestMethod.POST)
        public Map<String, String> sendSmsMessage(String phoneNumber) {
        return sendSmsService.sendSmsMessage(phoneNumber);
    }
}

SendSmsServiceImpl

package com.richfit.richfit.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SendSmsServiceImpl
 * @Description:
 * @Author BruthLi
 * @Date 2020/2/4
 * @Version V1.0
 **/
@Service
public class SendSmsServiceImpl implements SendSmsService {

    /**
     * 发送短信或验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public Map<String, String> sendSmsMessage(String phoneNumber) {
        String jsonCode = "{code:" + (int) ((Math.random() * 9 + 1) * 100000) + "}";
        CommonResponse response = null;
        Map<String, String> mapCode = new HashMap<>();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "*************", "*****************");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //电话PhoneNumbers和TemplateParam可以变,其他是在阿里云申请后都是固定值
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "BruthLi");
        request.putQueryParameter("TemplateCode", "SMS_183150435");
        //在这定义自己发送短信的内容 name不变:后面的值可以变
        //request.putQueryParameter("TemplateParam","{'name':'妈妈你吃饭了吗'}");
        //发送6位验证码
        request.putQueryParameter("TemplateParam", jsonCode);
        try {
            response = client.getCommonResponse(request);
            if (response.getHttpStatus() == 200) {
                mapCode.put("code", jsonCode);
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return mapCode;
    }
}

(六):报错
(1):在做下载的时候报一个:拒绝访问盘符拒绝访问

java.io.FileNotFoundException: E:\oilrichfit\richfit\src\main\resources\files\1580826234328.jpg (拒绝访问。)

这个错是因为对盘符没有访问权限或者对OSS bucket没有访问权限
解决方案在合适位置加如下代码:

//CannedAccessControlList有三个属性:Private(私有),PublicRead(公共读)
ossClient.setBucketAcl("tylgd", CannedAccessControlList.PublicReadWrite);

File file = new File(localFileAddressName,System.currentTimeMillis()+".mp4");
file.setWritable(true);

(2):在做下载的时候功能能实现但是前台仍然报错报一个(至今没有解决):org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON:

发布了163 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41987908/article/details/104179307