Springboot上传视频到阿里云OSS

x33g5p2x  于2022-02-28 转载在 Spring  
字(2.0k)|赞(0)|评价(0)|浏览(300)

一、准备

首先购买阿里云oss服务

https://www.aliyun.com/product/oss

配置以下几个参数

// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。	
private String endpoint = "";
// 阿里云账号AccessKey拥有所有API的访问权限,
private String AccessKey_ID = "";
private String AccessKey_Secret = "";
// 存储空间
private String BucketName = "";

二、代码

阿里云开发文档:

https://help.aliyun.com/document_detail/195870.html

导入依赖

<dependency>
       <groupId>com.aliyun.oss</groupId>
       <artifactId>aliyun-sdk-oss</artifactId>
       <version>3.10.2</version>
   </dependency>
@Data
public class Video  {

	private Integer id;
	// 标题
	private String title;
	// 简介
	private String into;
	// 封面
	private String cover;
	// 播放链接
	private String link;

controller

@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor
public class ApiUserController {

	private final OSSUtiles ossUtiles;

	@PostMapping("/aploadVideos")
	public Video videos(MultipartFile file, Video video,  HttpServletRequest request) throws IOException {
	
		String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
		String fileName = fileNamePrefix + "." + FilenameUtils.getExtension(file.getOriginalFilename());
	
		String link = ossUtiles.upload(file.getInputStream(), "videos", fileName);
	
		video.setLink(link);
		String cover = link + "?x-oss-pocess=video/snapshot,t_30000,f_jpg,w_0,h_0,m_fast,ar_auto";
		video.setCover(cover);
	
		return result;
	}

}

OSSUtiles 工具类

@Component
public class OSSUtiles {

	@Value("${oss.endpoint }")
	private String endpoint ;

	@Value("${oss.accessKeyId}")
	private String accesskeyId;

	@Value("${oss.secret}")
	private String secret;

	public String upload(InputStream inputStream, String path, String filename) {

		OSS ossClient = new OSSClientBuilder().build(endpoint, accesskeyId, secret);

		String bucketName = "yingxue-cloud";

		ossClient.createBucket(bucketName);

		String key = path + "/" + filename;
		ossClient.putObject(bucketName, key, inputStream);

		ossClient.shutdown();

		return "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + key;
	}
}

相关文章