1、导入阿里云OSS配置
在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。以3.15.1版本为例,在<dependencies>中加入如下内容:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
如果使用的是Java 9及以上的版本,则需要添加jaxb相关依赖。添加jaxb相关依赖示例代码如下:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
2、读取OSS配置
#阿里云oss配置
aliyun:
oss:
endpoint:
access-key-id:
access-key-secret:
bucket-name:
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
3、创建阿里云OSS工具类
@Data
@AllArgsConstructor
@Slf4j
public class AliyunOSSUntil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
public String upload(MultipartFile file) throws IOException {
// 避免文件覆盖
String originalFilename = file.getOriginalFilename();
String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//获取文件输入流
InputStream inputStream = file.getInputStream();
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
//上传文件
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,filename, inputStream);
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
}
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();
}
}
//文件访问路径
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;
return url;
}
}
4、创建配置类,用于创建AliOssUtil对象
@Configuration
public class AliyunOSSConfiguration {
private final Logger log = LoggerFactory.getLogger(AliyunOSSConfiguration.class);
@Bean
@ConditionalOnMissingBean
public AliyunOSSUntil aliyunOSSUntil(AliyunOssProperties aliyunOssProperties){
log.info("开始创建阿里云OSS工具类对象:{}",aliyunOssProperties);
return new AliyunOSSUntil(aliyunOssProperties.getEndpoint(),
aliyunOssProperties.getAccessKeyId(),
aliyunOssProperties.getAccessKeySecret(),
aliyunOssProperties.getBucketName());
}
}
5、创建文件上传控制类
@RestController
public class UploadController {
private final Logger log = LoggerFactory.getLogger(UploadController.class);
private AliyunOSSUntil aliyunOSSUntil;
@Autowired
public UploadController(AliyunOSSUntil aliyunOSSUntil) {
this.aliyunOSSUntil = aliyunOSSUntil;
}
@PostMapping("/upload")
public Result<String> upload(MultipartFile file){
try{
String url = aliyunOSSUntil.upload(file);
return Result.success(url);
} catch (IOException e) {
log.info("文件上传失败");
}
return Result.error("文件上传失败");
}
}