feat[文件上传]:oss阿里云对象存储集成

This commit is contained in:
2025-01-20 09:29:33 +08:00
parent 9960a696b4
commit 4ce91aa3ef
15 changed files with 357 additions and 18 deletions
@@ -0,0 +1,87 @@
package com.central.file.service.impl;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.model.OSSObject;
import com.central.common.constant.CommonConstant;
import com.central.file.model.FileInfo;
import com.central.oss.model.ObjectInfo;
import com.central.oss.properties.FileServerProperties;
import com.central.oss.template.OssTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author lsl
* @date 2025/1/13
* <p>
*/
@Service
@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS)
public class OssService extends AbstractIFileService {
@Resource
private OssTemplate ossTemplate;
@Override
protected String fileType() {
return FileServerProperties.TYPE_COS;
}
@Override
protected ObjectInfo uploadFile(MultipartFile file) {
return ossTemplate.upload(file);
}
@Override
protected ObjectInfo uploadFile(String name, InputStream inputStream) throws IOException {
return ossTemplate.upload(name, inputStream,inputStream.available(),"image/jpeg");
}
@Override
protected void deleteFile(String objectPath) {
OSSObject ossObject = parsePath(objectPath);
ossTemplate.delete(ossObject.getBucketName(), ossObject.getKey());
}
@Override
public void out(String id, OutputStream os) {
FileInfo fileInfo = baseMapper.selectById(id);
if (fileInfo != null) {
OSSObject ossObject = parsePath(fileInfo.getPath());
ossTemplate.out(ossObject.getBucketName(), ossObject.getKey(), os);
}
}
@Override
public String getViewUrl(String fileId) {
FileInfo fileInfo = baseMapper.selectById(fileId);
if (fileInfo != null) {
return ossTemplate.getViewUrl(fileInfo.getName());
}
return null;
}
@Override
public FileInfo getFileInfo(String id) {
return baseMapper.selectById(id);
}
private OSSObject parsePath(String path) {
OSSObject ossObject = new OSSObject();
if (StrUtil.isNotEmpty(path)) {
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
if (splitIndex != -1) {
ossObject.setBucketName(path.substring(0, splitIndex));
ossObject.setKey(path.substring(splitIndex + 1));
}
}
return ossObject;
}
}