阿里OSS 文件上传
pom依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.1</version>
</dependency>
yam 阿里配置
aliyun:
oss:
browserUrl: ${aliyun_oss_browserUrl}
bucket: ${aliyun_oss_tucket}
endpoint: ${aliyun_oss_endpoint}
accessKeyId: ${aliyun_oss_accessKeyId}
accessKeySecret: ${aliyun_oss_accessKeySecret}
获取配置信息
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliOssConfig {
private static String bucket;
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String browserUrl;
public void setBucket(String name) {
AliOssConfig.bucket = name;
}
public static String getBucket() {
return StringUtils.nvl(bucket, "");
}
public void setEndpoint(String name) {
AliOssConfig.endpoint = name;
}
public static String getEndpoint() {
return StringUtils.nvl(endpoint, "");
}
public void setAccessKeyId(String name) {
AliOssConfig.accessKeyId = name;
}
public static String getAccessKeyId() {
return StringUtils.nvl(accessKeyId, "");
}
public void setAccessKeySecret(String name) {
AliOssConfig.accessKeySecret = name;
}
public static String getAccessKeySecret() {
return StringUtils.nvl(accessKeySecret, "");
}
public void setBrowserUrl(String name) {
AliOssConfig.browserUrl = name;
}
public static String getBrowserUrl() {
return StringUtils.nvl(browserUrl, "");
}
}
关键代码
@Slf4j
public class AliOssUtils {
private static String endpoint = "";
private static String bucket = "";
private static String accessKeyId = "";
private static String accessKeySecret = "";
private static String browserUrl = "";
public static final String sperator = "/";
private static final String module = "[阿里OSS] ";
public static boolean initParam() {
endpoint = AliOssConfig.getEndpoint();
bucket = AliOssConfig.getBucket();
accessKeyId = AliOssConfig.getAccessKeyId();
accessKeySecret = AliOssConfig.getAccessKeySecret();
browserUrl = AliOssConfig.getBrowserUrl();
if (StringUtils.isEmpty(endpoint) || StringUtils.isEmpty(bucket) || StringUtils.isEmpty(accessKeyId) ||
StringUtils.isEmpty(accessKeySecret) || StringUtils.isEmpty(browserUrl)) {
log.error(module + "配置信息不能为空," +
"endpoint:{}, bucket:{},accessKeyId:{},accessKeySecret:{}, url:{}",
endpoint, bucket, accessKeyId, accessKeySecret, browserUrl);
return false;
}
return true;
}
/**
* 上传文件
* @param inputStream 文件流
* @param fileName 文件名包括后缀名
* @return
*/
public static String uploadFile(InputStream inputStream, String fileName) {
if (!initParam()) {
return "";
}
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
ossClient.putObject(bucket, fileName, inputStream);
ossClient.shutdown();
String filePath = browserUrl + fileName;
log.info(module + "上传文件成功, 路径:{}", filePath);
return filePath;
} catch (Exception e) {
e.printStackTrace();
log.error(module + "文件上传失败, 信息:{}", e.getMessage());
return null;
} finally {
ossClient.shutdown();
}
}
}