添加spring.fatories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.file.storage.config.oss.OssAutoConfiguration,\
com.demo.file.storage.config.fastdfs.FastdfsAutoConfiguration
oss 属性
@Data
@Component
@ConfigurationProperties(prefix = "demo.file.storage.oss")
public class OssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String folder;
private String domain;
}
oss 配置
@Configuration
@ConditionalOnClass(OSS.class)
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(prefix = "demo.file.storage.oss", name = "enable", havingValue = "true")
public class OssAutoConfiguration implements BeanFactoryAware {
private BeanFactory beanFactory;
private final OssProperties ossProperties;
public OssAutoConfiguration(final OssProperties ossProperties) {
this.ossProperties = ossProperties;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Bean(name = "ossClient")
public OSS createDefaultOssClient() {
return this.createOssClient(this.ossProperties);
}
@Bean(name = "ossFileStorageService")
public OssFileStorageService createDefaultOssFileService(@Qualifier("ossClient") final OSS ossClient, final OssProperties ossProperties) {
return this.createOssStorageService(ossClient,ossProperties);
}
private OSS createOssClient(final OssProperties properties) {
return new OSSClientBuilder().build(
properties.getEndpoint(),
properties.getAccessKeyId(),
properties.getAccessKeySecret());
}
private OssFileStorageService createOssStorageService(final OSS ossClient,final OssProperties ossProperties) {
return new OssFileStorageService(ossClient,ossProperties);
}
}
接口
public interface FileStorageService {
String upload(byte[] fileBytes, String fileName, String fileExtName) throws IOException;
String upload(InputStream fileInputStream, String fileName, String fileExtName) throws IOException;
/**
* 上传文件
*
* @param fileName 文件名
* @param fileBytes 文件byte数组
* @return
*/
FileUploadResponse upload(final String fileName, final byte[] fileBytes);
/**
* 上传文件
*
* @param fileName 文件名
* @param fileInputStream 文件流
* @return
*/
FileUploadResponse upload(final String fileName, final InputStream fileInputStream);
/**
* 上传文件
*
* @param fileName 文件名
* @param file 文件
* @return
*/
FileUploadResponse upload(final String fileName, final File file);
/**
* 下载文件
*
* @param fileKey 文件key
* @return
*/
byte[] download(String fileKey);
/**
* 文件下载到磁盘
*
* @param path 图片路径
* @param output 输出流 中包含要输出到磁盘的路径
* @return 失败(-1),成功(0)
*/
int download(final String path, final BufferedOutputStream output);
/**
* 删除文件
*
* @param fileName 文件的全部路径 如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
* @return
*/
boolean delete(final String fileName);
byte[] downloadObjectByProcess(String fileName, String process);
}
oss实现
@Slf4j
public class OssFileStorageService implements FileStorageService {
private final OSS ossClient;
private final OssProperties ossProperties;
public OssFileStorageService(final OSS ossClient, final OssProperties ossProperties) {
this.ossClient = ossClient;
this.ossProperties = ossProperties;
}
@Override
public String upload(final byte[] fileBytes, final String fileName, final String fileExtName) throws IOException {
return this.upload(new ByteArrayInputStream(fileBytes), fileName, fileExtName);
}
@Override
public String upload(final InputStream fileInputStream, String fileName, final String fileExtName) throws IOException {
if (!fileName.contains(".")) {
fileName = fileName + "." + fileExtName.replaceAll("\\.", "");
}
String result = null;
final PutObjectResult putObjectResult = this.ossClient.putObject(this.ossProperties.getBucketName(), this.ossProperties.getFolder() + "/" + fileName, fileInputStream);
if (Objects.nonNull(putObjectResult.getETag())) {
result = this.ossProperties.getDomain() + this.ossProperties.getFolder() + "/" + fileName;
}
return result;
}
@Override
public FileUploadResponse upload(final String fileName, final byte[] fileBytes) {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
return this.upload(fileName, inputStream);
}
@Override
public FileUploadResponse upload(final String fileName, final InputStream fileInputStream) {
final String key = this.ossProperties.getFolder() + "/" + fileName;
final PutObjectResult putObjectResult = this.ossClient.putObject(this.ossProperties.getBucketName(), key, fileInputStream);
String url = null;
if (Objects.nonNull(putObjectResult.getETag())) {
url = this.ossProperties.getDomain() + key;
}
final FileUploadResponse response = FileUploadResponse.builder().key(key).url(url).fileName(fileName).fileHash("").fileSize(0).build();
return response;
}
@Override
public FileUploadResponse upload(final String fileName, final File file) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (final FileNotFoundException e) {
log.error("upload file to oss error:{}", e);
}
return this.upload(fileName, fileInputStream);
}
@Override
public byte[] download(final String fileName) {
final OSSObject ossObject = this.ossClient.getObject(new GetObjectRequest(this.ossProperties.getBucketName(), this.ossProperties.getFolder() + "/" + fileName));
final InputStream inputStream = ossObject.getObjectContent();
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(inputStream);
} catch (final IOException e) {
log.error("Get object from ali cloud oss failed", e);
}
return bytes;
}
@Override
public int download(final String path, final BufferedOutputStream output) {
return 0;
}
@Override
public boolean delete(final String fileName) {
try {
this.ossClient.deleteObject(this.ossProperties.getBucketName(), this.ossProperties.getFolder() + "/" + fileName);
return true;
} catch (final Exception ex) {
log.error("delete oss object failure", ex);
return false;
}
}
/**
* 下载对象,传入阿里云OSS数据处理参数
*
* @param fileName
* @param process 数据处理参数
* @return
*/
@Override
public byte[] downloadObjectByProcess(final String fileName, final String process) {
final ProcessObjectRequest request = new ProcessObjectRequest(this.ossProperties.getBucketName(), this.ossProperties.getFolder() + "/" + fileName, process);
final GenericResult result = this.ossClient.processObject(request);
final ResponseMessage responseMessage = result.getResponse();
final InputStream inputStream = responseMessage.getContent();
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(inputStream);
} catch (final IOException e) {
log.error("get object from Ali cloud oss failed", e);
}
return bytes;
}
}
# demo-file-storage 使用说明
实现了使用OSS和FastDFS上传文件和下载文件。
## 引入依赖
com.demo.commons
demo-file-storage
1.0.3-SNAPSHOT
## application.properties配置文件
通过配置文件中的`demo.file.storage.*.enable`可以选择注入OSS或者FastDFS的实现
OSS配置
demo.file.storage.oss.enable=true
demo.file.storage.oss.endpoint=http://oss-cn-beijing.aliyuncs.com
demo.file.storage.oss.accessKeyId=L2342353465436N
demo.file.storage.oss.accessKeySecret=1163h45335345NMy453538n
demo.file.storage.oss.bucketName=img-dev
demo.file.storage.oss.folder=demo
demo.file.storage.oss.domain=http://demo.ltd/
FastDFS配置
demo.file.storage.fastdfs.enable=true
demo.file.storage.fastdfs.connect_timeout=60
demo.file.storage.fastdfs.network_timeout=60
demo.file.storage.fastdfs.charset=UTF-8
demo.file.storage.fastdfs.tracker_http_port=8888
demo.file.storage.fastdfs.anti_steal_token=no
demo.file.storage.fastdfs.secret_key=FastDFS1234567890
demo.file.storage.fastdfs.tracker_servers=1.0.0.1:22122
## 项目中注入服务
@Resource
private FileStorageService fileStorageService;
## 方法使用实例
详情见demo-commons-demo模块
public void upload() throws IOException {
String path = "/opt/test/apple.jpg";
File file = new File(path);
String upload = fileStorageService.upload(FileUtils.readFileToByteArray(file), "apple", "jpg");
log.info("upload url: {}",upload);
}
public void download() throws IOException {
String key = "apple";
byte[] download = fileStorageService.download(key);
String path = "/opt/test/apple2.jpg";
InputStream inputStreams = new ByteArrayInputStream(download);
Files.copy(inputStreams, Paths.get(path));
}
详细代码见github: https://github.com/Francis-Leo/Demo/tree/master/file-storage-demo