首先作为一个00后的程序员小白,集成第三方的东西真的是挺费劲的,百度之后写完发现全是坑。无奈自己用比较笨的方法写出来一套。奉献给各位新入职的程序员小白,如果项目要求不高可以使用。
第一步:引入依赖 集成sdk
第二步 : 配置yaml文件
第三步 : 写配置类
/**
* OBS桶名
*/
@Value("${obs.bucketname}")
private String bucketname;
/**
* 上传至OBS桶的存储对象名
*/
//@Value("${obs.config.objectname}")
private String objectname;
/**
* 连接OBS的endPoint
*/
@Value("${obs.endPoint}")
private String endPoint;
/**
* AK
*/
@Value("${obs.ak}")
private String ak;
/**
* SK
*/
@Value("${obs.sk}")
private String sk;
/** 图片位置 */
private String picLocation;
/** http或https 域名 */
@Value("${obs.domain-name}")
private String domainName;
public static String BUCKET_NAME;
public static String END_POINT;
public static String AK;
public static String SK;
public static String DOMAINNAME;
@Override
public void afterPropertiesSet()throws Exception {
BUCKET_NAME =this.bucketname;
END_POINT =this.endPoint;
AK =this.ak;
SK =this.sk;
DOMAINNAME =this.domainName;
}
最后写一个工具了类随意调用
public class ObsUtil {
/**
* 文件上传
* @param file 待上传的文件
* @param directory 指定存储的文件夹
* @return
*/
public static String uploadIdentity(MultipartFile file,String directory){
if (file ==null) {return"文件不可以为空!"; }
String url ="";
String endPoint =ObsConfig.END_POINT;
String ak =ObsConfig.AK;
String sk =ObsConfig.SK;
String bucketname =ObsConfig.BUCKET_NAME;
String domainName =ObsConfig.DOMAINNAME;
// 创建ObsClient实例
ObsClient obsClient =new ObsClient(ak,sk,endPoint);
String str = file.getOriginalFilename();
String name =str.substring(str.lastIndexOf(".")+1);
SnowflakeIdWorker idWorker =new SnowflakeIdWorker(0,0);
long id =idWorker.nextId();
String name1 =id +"."+name;
String objectName =directory +name1;
try {
// 待上传的本地文件路径,需要指定到具体的文件名
obsClient.putObject(bucketname,objectName, file.getInputStream());
url ="https://"+domainName +"/" +objectName;
}catch (IOException e) {
e.printStackTrace();
}
return url;
}
/**
*
* @param path
* @param directory
* @return
*/
public static String upload(String path,String directory){
if (path ==null) {return"文件不可以为空!"; }
String url ="";
String endPoint =ObsConfig.END_POINT;
String ak =ObsConfig.AK;
String sk =ObsConfig.SK;
String bucketname =ObsConfig.BUCKET_NAME;
// 创建ObsClient实例
ObsClient obsClient =new ObsClient(ak,sk,endPoint);
path = path.trim();
String objectName = directory+
path.substring(path.lastIndexOf("/")+1);
FileInputStream fis =null;
String url1 ="";
try {
fis =new FileInputStream(new File(path));
obsClient.putObject(ObsConfig.BUCKET_NAME,objectName, fis);
url1 =endPoint +"/" +objectName;
}catch (FileNotFoundException e) {
e.printStackTrace();
}
return url1;
}
}