阿里云对象存储OSS
Posted 伍妖捌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿里云对象存储OSS相关的知识,希望对你有一定的参考价值。
依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
属性配置
spring:
cloud:
alibaba:
access-key: xxxxxxxxxx
secret-key: xxxxxxxxxx
oss:
endpoint: oss-cn-beijing.aliyuncs.com
bucket: liuym-xxx
属性对应实体类
@Data
@Component
public class OssProperties {
@Value("${spring.cloud.alibaba.access-key}")
private String accessKey;
@Value("${spring.cloud.alibaba.secret-key}")
private String secretKey;
@Value("${spring.cloud.alibaba.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alibaba.oss.bucket}")
private String bucket;
}
Service
public interface FileService {
/**
* 阿里云OSS文件上传
*
* @param in 输入流
* @param module 模块名
* @param originalName 文件原始名字
* @return 访问路径
*/
String upload(InputStream in, String module, String originalName);
/**
* 阿里云OSS文件删除
*
* @param url 文件
*/
void removeFile(String url);
/**
* 阿里云OSS文件批量删除
*
* @param urls 文件集合
*/
void removeFiles(List<String> urls);
}
实现类
@Service
public class FileServiceImpl implements FileService {
@Autowired
private OssProperties oss;
@Override
public String upload(InputStream in, String module, String originalName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(oss.getEndpoint(), oss.getSecretKey(), oss.getAccessKey());
if (!ossClient.doesBucketExist(oss.getBucket())) {
ossClient.createBucket(oss.getBucket());
ossClient.setBucketAcl(oss.getBucket(), CannedAccessControlList.PublicRead);
}
//构建objectName:文件路径 avatar /2020/04/15/aaa.jpg
String folder = new DateTime().toString("yyyy/MM/dd");
String fileName = UUID.randomUUID().toString();
String fileExtension = originalName.substring(originalName.indexOf("."));
String objectName = module + "/" + folder + "/" + fileName + fileExtension;
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
ossClient.putObject(oss.getBucket(), objectName, in);
// 关闭OSSClient。
ossClient.shutdown();
return "https://" + oss.getBucket() + "." + oss.getEndpoint() + "/" + objectName;
}
@Override
public void removeFile(String url) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(oss.getEndpoint(), oss.getSecretKey(), oss.getAccessKey());
String host = "https://" + oss.getBucket() + "." + oss.getEndpoint() + "/";
String objectName = url.substring(host.length());
// 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
ossClient.deleteObject(oss.getBucket(), objectName);
// 关闭OSSClient。
ossClient.shutdown();
}
@Override
public void removeFiles(List<String> urls) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(oss.getEndpoint(), oss.getSecretKey(), oss.getAccessKey());
String host = "https://" + oss.getBucket() + "." + oss.getEndpoint() + "/";
List<String> keys = urls.stream().map(url -> url.substring(host.length())).collect(Collectors.toList());
// 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(oss.getBucket())
.withKeys(keys));
deleteObjectsResult.getDeletedObjects();
// 关闭OSSClient。
ossClient.shutdown();
}
}
访问接口
@Api(description = "阿里云文件管理")
@RestController
@RequestMapping("/oss/file")
@Slf4j
public class FileController {
@Autowired
private FileService fileService;
@ApiOperation("文件上传")
@PostMapping("upload")
public Result upload(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file, @ApiParam
(value = "模块名", required = true) @RequestParam("module") String module) {
try {
InputStream inputStream = file.getInputStream();
String originalFilename = file.getOriginalFilename();
String url = fileService.upload(inputStream, module, originalFilename);
return Result.ok().message("上传成功").data("url", url);
} catch (Exception e) {
log.error("{}: {}",ResultCode.FILE_UPLOAD_ERROR.getMessage(), e.getMessage());
throw new CustomException(ResultCode.FILE_UPLOAD_ERROR);
}
}
@ApiOperation(value = "文件删除")
@DeleteMapping("remove")
public Result removeFile(@ApiParam(value = "文件路径", required = true) @RequestBody String url) {
fileService.removeFile(url);
return Result.ok().message("文件删除成功");
}
@ApiOperation(value = "文件批量删除")
@DeleteMapping("removes")
public Result removeFiles(@ApiParam(value = "文件路径", required = true) @RequestBody List<String> urls) {
fileService.removeFiles(urls);
return Result.ok().message("文件删除成功");
}
}
以上是关于阿里云对象存储OSS的主要内容,如果未能解决你的问题,请参考以下文章