腾讯云上传步骤:
service-vod模块化中
①、参考文档,引入依赖
②、配置文件application.properties
③、创建工具类
- 初始化bean的时候读取配置文件
@Component
public class ConstantPropertiesUtil implements InitializingBean{@Value("${tencent.cos.file.region}")private String region;@Value("${tencent.cos.file.secretid}")private String secretId;@Value("${tencent.cos.file.secretKey}")private String secretKey;@Value("${tencent.cos.file.bucketname}")private String bucketName;//对上述私有变量进行公有化访问private static String END_POINT;private static String ACCESS_KEY_ID;private static String ACCESS_KEY_SECRET;private static String BUCKET_NAME;@Overridepublic void afterPropertiesSet()throws Exception{END_POINT = region;ACCESS_KEY_ID = secretId;ACCESS_KEY_SECRET = secretKey;BUCKET_NAME = bucketName;}
}
③、业务
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("/admin/vod/file")
@CrossOrigin
public class FileUploadController{@Autowiredprivate FileService fileService;@ApiOperation("文件上传")@PostMapping("upload")public Result uploadFile(MultipartFile file){String url = fileService.upload(file);return Result.ok(url).message("上传文件成功");}
}
@Service
public class FileServiceImpl implements FileService{@Overridepublic String upload(MultipartFile file){//初始化用户身份信息String secretId = ConstantPropertiesUilt.ACCESS_KEY_ID;String secretKey = ConstantPropertiesUtil.ACCESS_KEY_SECRET;COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);//设置bucket的地域Region region = new Region(ConstantPropertiesUtil.END_POINT);ClientConfig clientConfig = new ClientConfig(region);//这里建议设置使用https协议clientConfig.setHttpProtocol(HttpProtocol.https);//生成cos客户端COSClient cosClient = new COSClient(cred,clientConfig);//存储桶的命名格式为BuCKETnAME-APPID,此处填写的存储桶名称必需为此格式String bucketName = ConstantPropertiesUtil.BUCKET_NAME;//UUID+文件名,保证上传的文件唯一String key = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();//对上传文件分组,根据当前日期String dateTime = new DataTime.toString("yyyy/MM/dd");key = dateTime+"/"+key;try{//获取上传文件输入流InputStream inputStream = file.getInputtream();ObjectMetaData objectMetadata = new ObjectMetadata();PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,key,inputStream,objectMetadata);PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);String url = "https://" +bucketName+"."+"cos"+ConstantProperte.END_POINT+".myqcloud.com"+"/"+key;return url;}catch(Exception e){e.printStackTrace();}return null;}
}