记录:使用阿里云视频点播Vod实现上传本地视频

1.导入Maven依赖

<dependencies>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-vod</artifactId>
    </dependency>

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-sdk-vod-upload</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>

其中aliyun-sdk-vod-upload组件还未正式开源,需要手动导入jar包,首先在阿里云官方下载对应sdkjar包,解压之后再lib目录cmd使用命令:
mvn install:install-file -DgroupId=com.aliyun -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.12 -Dpackaging=jar -Dfile=aliyun-java-vod-upload-1.4.12.jar -Dmaven.repo.local=E:\apache-maven-3.3.9\repository

2、目录结构
在这里插入图片描述
application.yml:

server:
  port: 8003
spring:
  application:
    name: service-vod
  servlet:
    multipart:
      #最大上传单个文件大小:默认1M(不设置会报错)
      max-file-size: 1024MB
      #最大总上传的数据大小:默认10M
      max-request-size: 1024MB

  cloud:
    nacos:
      discovery:
        server-addr: 192.168.159.1xx:8848
aliyun:
  vod:
    file:
      keyid: LTAI4G8q7nBEsUb1NGc2i
      keysecret: 3FEJ5vh5EttqiiLdvijuvUWdt5
      region-id: cn-shanghai  #固定

#jasypt加密的密匙
jasypt:
  encryptor:
    password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ7

ConstantPropertiesUtils:

//方式一:
@Component //实现InitializingBean接口可以执行执行赋值后的一些逻辑(由于属性是private的)
public class ConstantPropertiesUtils implements InitializingBean {

    @Value("${aliyun.vod.file.keyid}")
    private String keyId;

    @Value("${aliyun.vod.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.vod.file.reginid}")
    private String reginId;

    /*定义公有静态常量*/
    public static String KEYID;
    public static String KEYSECRET;
    public static String REGINID;


    @Override
    public void afterPropertiesSet() throws Exception {
        KEYID = keyId;
        KEYSECRET = keySecret;
        REGINID = reginId;
    }
}

//或者方式二:
@Component
@ConfigurationProperties(prefix = "aliyun.vod.file")
@Data
public class ConstantPropertiesUtil {

    private String accessKeyId;

    private String accessKeySecret;

    private String regionId;
}
@Slf4j
@Service
public class VedioServiceImpl implements VedioService {

    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;
    ...
              UploadStreamRequest request =new UploadStreamRequest(constantPropertiesUtil.getAccessKeyId(),
                            constantPropertiesUtil.getAccessKeySecret(),
                            title,
                            originalFilename,
                            inputStream);
                            ...

VodApplication:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan(basePackages = {"com.coderkun"}) //扫描swagger等配置
public class VodApplication {
    public static void main(String[] args) {
        SpringApplication.run(VodApplication.class,args);
    }
}

VodController:

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    /*上传视频到阿里云*/
    @PostMapping("/uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file){
        //返回上传视频返回的id
        String videoId = vodService.uploadAlyVideo(file);
        return R.ok().data("data",videoId);
    }
    //根据视频id删除视频
    @DeleteMapping("delete/{vedioId}")
    public ResponseResult deleteByVedioId(@PathVariable String vedioId){
        final String remove = vedioService.remove(vedioId);
        return ResponseResult.success().message("视频删除成功").data("remove",remove);
    }
	//批量删除视频
    @DeleteMapping("deleteBatch/{videoSourceIds}")
    public ResponseResult deleteBatch(@PathVariable List<String> videoSourceIds){
        String vedioIdArray = StringUtils.join(videoSourceIds.toArray(), ",");
        final String remove = vedioService.remove(vedioIdArray);
        return ResponseResult.success().message("视频删除成功").data("remove",remove);
    }
}

VodService:

public interface VodService {
    String uploadAlyVideo(MultipartFile file);
}

VodServiceImpl:

@Service
public class VodServiceImpl implements VodService {

    /*上传视频到阿里云*/
    @Override
    public String uploadAlyVideo(MultipartFile file) {
        try {
            String accessKeyId = ConstantPropertiesUtils.KEYID;
            String accessKeySecret = ConstantPropertiesUtils.KEYSECRET;

            String fileName = file.getOriginalFilename();  //原始文件名称
            String title = fileName.substring(0,fileName.lastIndexOf("."));   //上传之后文件名称
            InputStream in = file.getInputStream();

            //上传视频的方法
            UploadStreamRequest request = null;

            request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, in);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();

            }
            return videoId;  //将视频id返回,保存到数据库中而不是保存视频地址。
        } catch (IOException e) {
            throw new GuliException(20001, "上传时出现异常");
            return null;
        }
	//删除视频
    @Override
    public String remove(String vedioId) {
        String requestId ;
        try {
        	//初始化
            DefaultAcsClient client = AliyunVodSdkUtil.initVodClient(
                    ConstantPropertiesUtils.KEYID,
                    ConstantPropertiesUtils.KEYSECRET,
                    ConstantPropertiesUtils.REGINID ;
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(vedioId);
            DeleteVideoResponse response = client.getAcsResponse(request);
            requestId = response.getRequestId();
        }catch (ClientException e){
            throw new GuliException(20001,e.getMessage());
        }
        return requestId;   //返回请求id
      }
    }

工具类AliyunVodSdkUtil :

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;

public class AliyunVodSdkUtil {
    public static DefaultAcsClient initVodClient(String regionId,String accessKey,String accessSecret){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
}

欢迎关注公众号Java技术大联盟,会不定期分享BAT面试资料等福利。

在这里插入图片描述


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值