1.对象存储概述
文件上传,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发抖音、发朋友圈都用到了文件上传功能。
实现文件上传服务,需要有存储的支持,解决方案有以下几种:
存储方式 | 优点 | 缺点 |
---|---|---|
直接保存到硬盘 | 开发便捷,成本低 | 扩容困难 |
分布式文件系统 | 容易实现扩容 | 开发复杂,需要成熟产品支持 |
第三方存储服务 | 开发简单,强大功能, 免维护 | 付费 |
2.阿里云对象存储OSS
阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台欢迎登录阿里云,全球领先的云计算及人工智能科技公司,阿里云为200多个国家和地区的企业、开发者和政府机构提供云计算基础服务及解决方案。阿里云云计算、安全、大数据、人工智能、企业应用、物联网等云计算服务。https://oss.console.aliyun.com/
2.1 阿里云对象存储OSS配置
2.1.1 创建OSS Bucket
登录阿里云控制台,申请ECS服务器、申请对象存储OSS、在OSS管理页面创建一个Bucket,Bucket是存储空间的容器,类似于文件夹。选择Bucket的地域、访问权限等设置。
2.1.2 获取AccessKey
在阿里云控制台获取AccessKey ID和AccessKey Secret,这是访问OSS的凭证。
2.2 项目中使用对象存储OSS
2.2.1 配置AccessKey ID和AccessKey Secret
sky:
alioss:
endpoint: oss-cn-chengdu.aliyuncs.com
access-key-secret: B4CZYBn9zyoKjQzdN5sQNvdxaWJSuy
access-key-id: LTAI5tAKNiTtEJaPdE3omMi3
bucket-name: luobeilearn
2.2.2 配置配置类
@Configuration
@Slf4j
public class OssConfiguration {
@Bean
@ConditionalOnMissingBean
public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
log.info("开始上传阿里云文件上传工具类对象:{}",aliOssProperties);
return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());
}
}
2.2.3 创建阿里云属性类
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2.2.4 创建工具类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
2.2.5 在Controller中使用
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
@PostMapping("/upload")
@ApiOperation("文件上传")
public Result<String> upload(MultipartFile file){
log.info("文件上传");
try {
//原始文件名
String originalFilename = file.getOriginalFilename();
//截取原始文件名后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = UUID.randomUUID().toString()+substring;
String filePath = aliOssUtil.upload(file.getBytes(),objectName);
return Result.success(filePath);
} catch (IOException e) {
log.error("文件上传失败:{}",e);
}
return Result.error(MessageConstant.UPLOAD_FAILED);
}
}