使用minio的方式
引入依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.5.2</version>
</dependency>
配置minio客户端
配置类
@Data
@ConfigurationProperties(prefix="spzx.minio") //读取节点
public class MinioProperties {
private String endpointUrl;
private String accessKey;
private String secreKey;
private String bucketName;
}
配置属性
spzx:
minio:
endpointUrl: http://127.0.0.1:9000
accessKey: minioadmin
secreKey: minioadmin
bucketName: spzx-bucket
创建服务并进行文件上传
存储图片文件并返回路径
@Service
public class FileUploadServiceImpl implements FileUploadService {
@Autowired
private MinioProperties minioProperties;
@Override
public String upload(MultipartFile multipartFile) {
try {
// 创建一个Minio的客户端对象
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpointUrl())
.credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
.build();
// 判断桶是否存在
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
if (!found) { // 如果不存在,那么此时就创建一个新的桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
} else { // 如果存在打印信息
System.out.println("Bucket 'spzx-bucket' already exists.");
}
// 设置存储对象名称
String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
String uuid = UUID.randomUUID().toString().replace("-", "");
//20230801/443e1e772bef482c95be28704bec58a901.jpg
String fileName = dateDir+"/"+uuid+multipartFile.getOriginalFilename();
System.out.println(fileName);
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
.object(fileName)
.build();
minioClient.putObject(putObjectArgs) ;
return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;
} catch (Exception e) {
throw new GuiguException(ResultCodeEnum.SYSTEM_ERROR);
}
}
}
使用阿里云OSS对象存储服务
引入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.sdk.oss}</version>
</dependency>
配置客户端
配置类
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
配置文件
sky:
alioss:
endpoint: oss-cn-beijing.aliyuncs.com
access-key-id: LTAI5tBCdFW1gBAgvzT5K4CH
access-key-secret: QIdc2BQr4KHKJ1Qdwh3OUPNvQk2dnp
bucket-name: sky-demo02
工具类
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} 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();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
文件上传
/**
* 通用接口
*/
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
@PostMapping("/upload")
@ApiOperation("文件上传")
public Result<String> upload(MultipartFile file){//参数名和前端提交的要一样
log.info("文件上传: ",file);
try {
//原始文件名
String originalFileName = file.getOriginalFilename();
//截取原始文件名后缀
String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
//新文件名称
String objectName = UUID.randomUUID().toString() + extension;
String filePath = aliOssUtil.upload(file.getBytes(), objectName);
return Result.success(filePath);
} catch (Exception e) {
log.error("文件上传失败: {}",e);
}
return Result.error(MessageConstant.UPLOAD_FAILED);
}
}