作者:粪青12_601 | 来源:互联网 | 2023-10-13 13:35
SpringBoot整合阿里云OSS实现单个图片上传和批量上传
1、首先申请阿里云OSS账号
2、application.yml
aliyun:
oss:
endpoint: oss-cn-hangzhou.aliyuncs.com # oss对外服务的访问域名
accessKeyId: xxx # 访问身份验证中用到用户标识
accessKeySecret: xxx # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
bucketName: zhuicat-dev # oss的存储空间
3、OSS工具类
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yougong.common.exception.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Component
public class OssUtils {
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String secretAccessKey;
@Value("${aliyun.oss.endpoint}")
private String endPoint;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
public String uploadOneFile(MultipartFile file) {
if (!(file.getOriginalFilename().endsWith(".png")) && !(file.getOriginalFilename().endsWith(".jpg"))) {
throw new ApiException("文件类型错误,只能为png或者jpg");
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
//设置文件名
String fileName = new DateTime().toString("yyyy/MM/dd")
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
// System.out.println(url);
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public List uploadArrayFile(MultipartFile[] files) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
List list = new ArrayList<>();
try {
//设置文件名
for (MultipartFile file : files) {
String fileName = new DateTime().toString("yyyy/MM/dd")
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
// System.out.println(url);
list.add(url);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return list;
}
public boolean deleteFile(String fileUrl) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
/** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
* 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
* 则完整路径就是:2022/08/abc.jpg
*/
int begin = ("http://" + bucketName + "." + endPoint + "/").length(); //找到文件路径的开始下标
String deleteUrl = fileUrl.substring(begin);
try {
// 删除文件请求
ossClient.deleteObject(bucketName, deleteUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
4、Controller层
import com.yougong.admin.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/oss")
public class OssController {
@Autowired
OssUtils ossUtils;
@PostMapping("uploadOneFile")
public String uploadFile(MultipartFile file) {
//返回上传oss的url
return ossUtils.uploadOneFile(file);
}
@PostMapping("uploadArrayFile")
public List uploadArrayFile(MultipartFile[] files) {
//返回上传oss的url
return ossUtils.uploadArrayFile(files);
}
@PostMapping("deleteFile")
public boolean deleteFile( String fileUrl) {
//返回是否删除成功
return ossUtils.deleteFile(fileUrl);
}
}
5、service层
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yougong.common.exception.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Component
public class OssUtils {
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String secretAccessKey;
@Value("${aliyun.oss.endpoint}")
private String endPoint;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
public String uploadOneFile(MultipartFile file) {
if (!(file.getOriginalFilename().endsWith(".png")) && !(file.getOriginalFilename().endsWith(".jpg"))) {
throw new ApiException("文件类型错误,只能为png或者jpg");
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
//设置文件名
String fileName = new DateTime().toString("yyyy/MM/dd")
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
// System.out.println(url);
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public List uploadArrayFile(MultipartFile[] files) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
List list = new ArrayList<>();
try {
//设置文件名
for (MultipartFile file : files) {
String fileName = new DateTime().toString("yyyy/MM/dd")
+ UUID.randomUUID().toString().replace("-", "")
+ file.getOriginalFilename();
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName, file.getInputStream());
String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
// System.out.println(url);
list.add(url);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return list;
}
public boolean deleteFile(String fileUrl) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);
/** oss删除文件是根据文件完成路径删除的,但文件完整路径中不能包含Bucket名称。
* 比如文件路径为:http://edu-czf.oss-cn-guangzhou.aliyuncs.com/2022/08/abc.jpg",
* 则完整路径就是:2022/08/abc.jpg
*/
int begin = ("http://" + bucketName + "." + endPoint + "/").length(); //找到文件路径的开始下标
String deleteUrl = fileUrl.substring(begin);
try {
// 删除文件请求
ossClient.deleteObject(bucketName, deleteUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
6、测试
7、查看阿里云OSS
8、直接访问返回的地址
9、解决8 的问题
10、再次测试
整合完毕!!!!