第一步:先引用oss依赖 这里用的是3.15.1 话不多说 黏代码
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency>
第二步:在properties中设置oss的ID key等秘钥
alioss.ossEndpoint= alioss.accessId= alioss.accessKey= alioss.ossEndpointUrl= alioss.bucketName=
第三步:创建类并引用属性
@Component
@Configuration
@Data
public class AliyunOssPropertiesBean {
@Value("${alioss.ossEndpointUrl}")
private String ossEndpointUrl;
@Value("${alioss.accessId}")
private String accessKeyId;
@Value("${alioss.accessKey}")
private String accessKey;
@Value("${alioss.bucketName}")
private String bucketName;
}
第四步:创建oss工具类 实现上传和下载的功能
@Slf4j
@Service
public class OSSFileService {
private static final String BUCKET_PRE = "order_import";
private static final String HTTP_PRE = "https://";
private static final String DIAGONAL = "/";
private static final String SPOT = ".";
@Autowired
private AliyunOssPropertiesBean aliyunOssPropertiesBean;
public String upload(MultipartFile file) {
String endpoint = aliyunOssPropertiesBean.getOssEndpointUrl();
String accessKeyId = aliyunOssPropertiesBean.getAccessKeyId();
String accessKeySecret = aliyunOssPropertiesBean.getAccessKey();
String bucketName = aliyunOssPropertiesBean.getBucketName();
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
String timeUrl = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
fileName = BUCKET_PRE + DIAGONAL + fileName + timeUrl;
//调用方法实现上传
ossClient.putObject(bucketName, fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//上传之后文件路径
String url = HTTP_PRE + bucketName + SPOT + endpoint + DIAGONAL + fileName;
//返回
return url;
} catch (IOException e) {
log.error("OSS上传异常:{}", e);
return null;
}
}
public String upload(ByteArrayOutputStream outputStream, String originalFilename) {
String endpoint = aliyunOssPropertiesBean.getOssEndpointUrl();
String accessKeyId = aliyunOssPropertiesBean.getAccessKeyId();
String accessKeySecret = aliyunOssPropertiesBean.getAccessKey();
String bucketName = aliyunOssPropertiesBean.getBucketName();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
String timeUrl = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
String fileName = BUCKET_PRE + DIAGONAL + timeUrl + originalFilename;
//调用方法实现上传
ossClient.putObject(bucketName, fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//上传之后文件路径
return HTTP_PRE + bucketName + SPOT + endpoint + DIAGONAL + fileName;
}
}