第一步:引入依赖

引入项目所需要的依赖

 <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- Spring Cloud Alibaba 单点项目可以移除 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- Ali Cloud -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Projects -->
        <dependency>
            <groupId>com.greatdata</groupId>
            <artifactId>cloud-oss-feign</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.greatdata</groupId>
            <artifactId>commons-util</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>


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

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

        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>

        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
        <!-- 注意:这个包在maven仓库中没有,需要本地打包才能引入 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-sdk-vod-upload</artifactId>
            <version>1.4.12</version>
        </dependency>

第二步:编写工具类

/**
 * <p>
 * Description:
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2020-07-14 15:18
 * @see com.greatdata.vod.utils
 */
@Component
public class ConstantVodUtil implements InitializingBean {

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


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

    /**
     * 阿里云Key
     */
    public static String ACCESS_KEY_ID;

    /**
     * 密钥
     */
    public static String ACCESS_KEY_SECRET;



    /**
     * Description: 初始化
     * @Param: []
     * @Return:
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        ACCESS_KEY_ID = keyid;
        ACCESS_KEY_SECRET = keysecret;
    }
}

第三步:编写视频上传接口

/**
 * <p>
 * Description:视频上传接口
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2020-07-14 11:30
 * @see com.greatdata.provider
 */
public interface VodUploadService {

    /**
     * Description: 视频上传接口
     * @Param: [file]
     * @Return: {@link java.lang.String}
     */
    Map<String,String> uploadVideoAly(MultipartFile file);

}

第四步:编写视频上传实现类

/**
 * <p>
 * Description:视频上传实现类
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2020-07-14 11:31
 * @see com.greatdata.provider.service
 */
@Service
public class VodUploadServiceImpl implements VodUploadService {

    /**
     * Description: 视频上传实现方法
     * @Param: [file]
     * @Return: {@link java.lang.String}
     */
    @Override
    public Map<String,String> uploadVideoAly(MultipartFile file) {
        try {
            /**原文件名*/
            String fileName = file.getOriginalFilename();

            /**上传之后的文件名*/ //原文件名.mp4 只截取文件名
            String title = fileName.substring(0,fileName.lastIndexOf("."));

            System.out.println("title="+title);

            /**输入流*/
            InputStream inputStream = file.getInputStream();

            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtil.ACCESS_KEY_ID,ConstantVodUtil.ACCESS_KEY_SECRET, title, fileName, inputStream);

            System.out.println("ConstantVodUtil.ACCESS_KEY_ID="+ConstantVodUtil.ACCESS_KEY_ID);
            System.out.println("ConstantVodUtil.ACCESS_KEY_SECRE="+ConstantVodUtil.ACCESS_KEY_SECRET);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID

            String VideoId = response.getRequestId();
            Map<String,String> map = new HashMap<>();
            map.put("VideoId",VideoId);
            map.put("title",title);
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");

            } else { //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
             return map;
                     
        } catch (Exception e) {
            System.out.println("进入了报错区");
            e.printStackTrace();
            return null;
        }
    }
}

通用工具类

/**
 * 通用数据传输对象
 * <p>
 * Description:
 * </p>
 *
 * @author Songzixian
 * @version v1.0.0
 * @date 2020-07-26 04:43:54
 * @see com.songzixian.commons.dto
 */
@Data
public class ResponseResult<T> implements Serializable {


    private static final long serialVersionUID = -3999803560577989187L;
    /**
     * 状态码
     */
    private Integer code;

    /**
     * 消息
     */
    private String message;

    /**
     * 返回对象
     */
    private T data;

    public ResponseResult() {
        super();
    }

    public ResponseResult(Integer code) {
        super();
        this.code = code;
    }

    public ResponseResult(Integer code, String message) {
        super();
        this.code = code;
        this.message = message;
    }

    public ResponseResult(Integer code, Throwable throwable) {
        super();
        this.code = code;
        this.message = throwable.getMessage();
    }

    public ResponseResult(Integer code, T data) {
        super();
        this.code = code;
        this.data = data;
    }

    public ResponseResult(Integer code, String message, T data) {
        super();
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((data == null) ? 0 : data.hashCode());
        result = prime * result + ((message == null) ? 0 : message.hashCode());
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        ResponseResult<?> other = (ResponseResult<?>) obj;
        if (data == null) {
            if (other.data != null) {
                return false;
            }
        } else if (!data.equals(other.data)) {
            return false;
        }
        if (message == null) {
            if (other.message != null) {
                return false;
            }
        } else if (!message.equals(other.message)) {
            return false;
        }
        if (code == null) {
            if (other.code != null) {
                return false;
            }
        } else if (!code.equals(other.code)) {
            return false;
        }
        return true;
    }

    /**
     * 通用状态码
     * <p>
     * Description:
     * </p>
     *
     * @author Lusifer
     * @version v1.0.0
     * @date 2019-07-30 05:02:49
     * @see
     */
    public class CodeStatus {
        /**
         * 请求成功
         */
        public static final int OK = 20000;

        /**
         * 请求失败
         */
        public static final int FAIL = 20002;

        /**
         * 熔断请求
         */
        public static final int BREAKING = 20004;

        /**
         * 非法请求
         */
        public static final int ILLEGAL_REQUEST = 50000;

        /**
         * 非法令牌
         */
        public static final int ILLEGAL_TOKEN = 50008;

        /**
         * 其他客户登录
         */
        public static final int OTHER_CLIENTS_LOGGED_IN = 50012;

        /**
         * 令牌已过期
         */
        public static final int TOKEN_EXPIRED = 50014;
    }
}  

第五步:编程视频上传Controller

/**
 * 视频点播上传
 * <p>
 * Description:实现本地视频上传只阿里云
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2020-07-14 11:21
 * @see com.greatdata.vod.controller
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class VodUploadController {

    @Autowired
    private VodUploadService vodUploadService;

    /**
     * Description: 本地视频上传到阿里云
     * @Param: [file]
     * @Return: {@link ResponseResult<File>}
     */
    @PostMapping("uploadVideoAly")
    public ResponseResult<MultipartFile> uploadVideoAly(MultipartFile file){
        try {
            Map<String, String> videoInfo = vodUploadService.uploadVideoAly(file);
            if (videoInfo.size()==0||videoInfo==null){
                return new ResponseResult(ResponseResult.CodeStatus.OK,"上传错误,获取不到视频ID");
            }

            return new ResponseResult(ResponseResult.CodeStatus.OK,"视频成功",videoInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(ResponseResult.CodeStatus.OK,"视频上传失败,请重试");
        }
    }
}

第六步:编写application配置文件

# 服务端口
server.port=1002
# 服务名
spring.application.name=cloud-vod-service

# 环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 vod
#不同的服务器,地址不同
aliyun.vod.file.keyid=LTAI4FvvVEWiTJ3GNJJqJnk7
aliyun.vod.file.keysecret=9st82dv7EvFk9mTjYO1XXbM632fRbG

# 最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB
# 最大置总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB

第七步:编写启动类

/**
 * 阿里云视频点播启动类
 * <p>
 * Description:
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2020-07-1 10:05
 * @see com.greatdata.vod.controller
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan(basePackages = {"com.greatdata"})
public class CloudVodApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudVodApplication.class,args);
    }

}

第八步:测试上传

打开 PostMan,新增访问地址 http://localhost:10002/uploadVideoAly
增加 Headers 配置

KEY: Content-Type
VALUE: multipart/form-data

Spring Boot实现阿里云视频点播视频上传实战1.png
点击Body
Spring Boot实现阿里云视频点播视频上传实战2.png
上传成功后打开阿里云视频点播控制台,就能看到刚刚上传的文件了
Spring Boot实现阿里云视频点播视频上传实战3.png

Last modification:July 15, 2020
如果觉得这篇技术文章对你有用,请随意赞赏