1)阿里云配置属性类--读取配置文件中的配置项并封装为Java对象
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2)在配置文件中配置阿里云的相关属性
sky:
alioss:
endpoint: *********
access-key-id: ************
access-key-secret: ********
bucket-name: *******
3)AliOssUtil工具类
package com.sky.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
@Data
@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();
}
}
4)配置类用于创建AliOssUtil对象
@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());
}
}
5)文件上传接口
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
/**
* 图片文件上传
*
* @param imgFile
* @return
*/
@PostMapping("/upload")
public Result<String> upload(MultipartFile imgFile) {
log.info("文件上传:{}", imgFile);
try {
//获取原始文件名
String originalFilename = imgFile.getOriginalFilename();
//截取原始文件的后缀
String end = originalFilename.substring(originalFilename.lastIndexOf("."));
//生成新的不重复的文件名
String fileNewname = UUID.randomUUID().toString() + end;
//文件的访问路径
String filePath = aliOssUtil.upload(imgFile.getBytes(), fileNewname);
//只要点击上传图片,不管确不确定。
redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,fileNewname);
log.info("在Redis中的名称是:{}",fileNewname);
return Result.success(filePath,MessageConstant.PIC_UPLOAD_SUCCESS);
} catch (IOException e) {
log.error("文件上传失败:{}", e);
}
return Result.error(MessageConstant.PIC_UPLOAD_FAIL);
}
}