概述
1.接口
package com.hjl.cloud;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.util.UUID;
/**
* 云存储(支持七牛、阿里云、腾讯云)
*/
public abstract class CloudStorageService {
/**
* 云存储配置信息
*/
CloudStorageConfig config;
public int getService() {
return config.getType();
}
/**
* 文件路径
*
* @param prefix 前缀
* @param suffix 后缀
* @return 返回上传路径
*/
public String getPath(String prefix, String suffix) {
// 生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-" , "");
// 文件路径
String path = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/" + uuid;
if (StringUtils.isNotBlank(prefix)) {
path = prefix + "/" + path;
}
return path + suffix;
}
/**
* 文件上传
*
* @param data 文件字节数组
* @param path 文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(byte[] data, String path);
/**
* 文件上传
*
* @param data
文件字节数组
* @param suffix 后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(byte[] data, String suffix);
/**
* 文件上传
*
* @param inputStream 字节流
* @param path
文件路径,包含文件名
* @return 返回http地址
*/
public abstract String upload(InputStream inputStream, String path);
/**
* 文件上传
*
* @param inputStream 字节流
* @param suffix
后缀
* @return 返回http地址
*/
public abstract String uploadSuffix(InputStream inputStream, String suffix);
}
2.腾讯云
package com.hjl.cloud;
import com.hjl.OssException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* 腾讯云存储
*/
public class QcloudCloudStorageService extends CloudStorageService {
private COSClient client;
public QcloudCloudStorageService(CloudStorageConfig config) {
this.config = config;
// 初始化
init();
}
private void init() {
Credentials credentials = new Credentials(config.getQcloudAppId(), config.getQcloudSecretId(),
config.getQcloudSecretKey());
// 初始化客户端配置
ClientConfig clientConfig = new ClientConfig();
// 设置bucket所在的区域,华南:gz 华北:tj 华东:sh
clientConfig.setRegion(config.getQcloudRegion());
client = new COSClient(clientConfig, credentials);
}
@Override
public String upload(byte[] data, String path) {
// 腾讯云必需要以"/"开头
if (!path.startsWith("/")) {
path = "/" + path;
}
// 上传到腾讯云
UploadFileRequest request = new UploadFileRequest(config.getQcloudBucketName(), path, data);
String response = client.uploadFile(request);
JSONObject jsonObject = JSONObject.fromObject(response);
if (jsonObject.getInt("code") != 0) {
throw new OssException("文件上传失败," + jsonObject.getString("message"));
}
return config.getQcloudDomain() + path;
}
@Override
public String upload(InputStream inputStream, String path) {
try {
byte[] data = IOUtils.toByteArray(inputStream);
return this.upload(data, path);
} catch (IOException e) {
throw new OssException("上传文件失败");
}
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQcloudPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
}
}
3.阿里云
package com.hjl.cloud;
import com.aliyun.oss.OSSClient;
import com.hjl.OssException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* 阿里云存储
*/
public class AliyunCloudStorageService extends CloudStorageService {
private OSSClient client;
public AliyunCloudStorageService(CloudStorageConfig config) {
this.config = config;
// 初始化
init();
}
private void init() {
client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
config.getAliyunAccessKeySecret());
}
@Override
public String upload(byte[] data, String path) {
return upload(new ByteArrayInputStream(data), path);
}
@Override
public String upload(InputStream inputStream, String path) {
try {
client.putObject(config.getAliyunBucketName(), path, inputStream);
} catch (Exception e) {
throw new OssException("上传文件失败,请检查配置信息");
}
return config.getAliyunDomain() + "/" + path;
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getAliyunPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getAliyunPrefix(), suffix));
}
}
4.七牛
package com.hjl.cloud;
import com.hjl.OssException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* 七牛云存储
*/
public class QiniuCloudStorageService extends CloudStorageService {
private UploadManager uploadManager;
private String token;
public QiniuCloudStorageService(CloudStorageConfig config) {
this.config = config;
// 初始化
init();
}
private void init() {
uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey())
.uploadToken(config.getQiniuBucketName());
}
@Override
public String upload(byte[] data, String path) {
try {
Response res = uploadManager.put(data, path, token);
if (!res.isOK()) {
throw new RuntimeException("上传七牛出错:" + res.toString());
}
} catch (Exception e) {
throw new OssException("上传文件失败,请核对七牛配置信息");
}
return config.getQiniuDomain() + "/" + path;
}
@Override
public String upload(InputStream inputStream, String path) {
try {
byte[] data = IOUtils.toByteArray(inputStream);
return this.upload(data, path);
} catch (IOException e) {
throw new OssException("上传文件失败");
}
}
@Override
public String uploadSuffix(byte[] data, String suffix) {
return upload(data, getPath(config.getQiniuPrefix(), suffix));
}
@Override
public String uploadSuffix(InputStream inputStream, String suffix) {
return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
}
}
5.异常类
package com.hjl;
/**
* OSS信息异常类
*
* @author hjl
*/
public class OssException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OssException(String msg) {
super(msg);
}
}
6.主要的jar包(工具jar自行导入)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>4.4</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
7.工厂类
package com.hjl.cloud;
import com.alibaba.fastjson.JSON;
import com.hjl.cloud.CloudConstant.CloudService;
import com.hjl.utils.SpringUtils;
import com.hjl.service.ConfigService;
/**
* 文件上传Factory
*/
public final class OSSFactory {
private static ConfigService configService;
static {
OSSFactory.configService= (ConfigService) SpringUtils.getBean(ConfigService.class);
}
public static CloudStorageService build() {
//从数据库中查询oss的domain和key信息...
//json字符串
/**
{
"type":1,
"qiniuDomain":"",
"qiniuPrefix":"",
"qiniuAccessKey":"",
"qiniuSecretKey":"",
"qiniuBucketName":"",
"aliyunDomain":"",
"aliyunPrefix":"",
"aliyunEndPoint":"",
"aliyunAccessKeyId":"",
"aliyunAccessKeySecret":"",
"aliyunBucketName":"",
"qcloudDomain":"",
"qcloudPrefix":"",
"qcloudSecretId":"",
"qcloudBucketName":"",
"qcloudRegion":""
}
**/
String jsonconfig = configService.getConfigByKey(CloudConstant.CLOUD_STORAGE_CONFIG_KEY);
// 获取云存储配置信息
CloudStorageConfig config = JSON.parseObject(jsonconfig, CloudStorageConfig.class);
if (config.getType() == CloudService.QINIU.getValue()) {
return new QiniuCloudStorageService(config);
} else if (config.getType() == CloudService.ALIYUN.getValue()) {
return new AliyunCloudStorageService(config);
} else if (config.getType() == CloudService.QCLOUD.getValue()) {
return new QcloudCloudStorageService(config);
}
return null;
}
}
package com.hjl.cloud;
public class CloudConstant {
/**
* 云存储配置KEY
*/
public final static String CLOUD_STORAGE_CONFIG_KEY = "oss.cloudStorage";
/**
* 云服务商
*/
public enum CloudService {
/**
* 七牛云
*/
QINIU(1),
/**
* 阿里云
*/
ALIYUN(2),
/**
* 腾讯云
*/
QCLOUD(3);
private int value;
CloudService(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}
package com.hjl.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*
* @author hjl
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
/**
* Spring应用上下文环境
*/
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
}
package com.hjl.cloud;
import com.hjl.cloud.valdator.AliyunGroup;
import com.hjl.cloud.valdator.QcloudGroup;
import com.hjl.cloud.valdator.QiniuGroup;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
/**
* 云存储配置信息
*/
@Data
public class CloudStorageConfig implements Serializable {
//
private static final long serialVersionUID = 1L;
// 类型 1:七牛 2:阿里云 3:腾讯云
@Range(min = 1, max = 3, message = "类型错误")
private Integer type;
// 七牛绑定的域名
@NotBlank(message = "七牛绑定的域名不能为空" , groups = QiniuGroup.class)
@URL(message = "七牛绑定的域名格式不正确" , groups = QiniuGroup.class)
private String qiniuDomain;
// 七牛路径前缀
private String qiniuPrefix;
// 七牛ACCESS_KEY
@NotBlank(message = "七牛AccessKey不能为空" , groups = QiniuGroup.class)
private String qiniuAccessKey;
// 七牛SECRET_KEY
@NotBlank(message = "七牛SecretKey不能为空" , groups = QiniuGroup.class)
private String qiniuSecretKey;
// 七牛存储空间名
@NotBlank(message = "七牛空间名不能为空" , groups = QiniuGroup.class)
private String qiniuBucketName;
// 阿里云绑定的域名
@NotBlank(message = "阿里云绑定的域名不能为空" , groups = AliyunGroup.class)
@URL(message = "阿里云绑定的域名格式不正确" , groups = AliyunGroup.class)
private String aliyunDomain;
// 阿里云路径前缀
@Pattern(regexp = "^[^(/|\)](.*[^(/|\)])?$" , message = "阿里云路径前缀不能'/'或者''开头或者结尾" , groups = AliyunGroup.class)
private String aliyunPrefix;
// 阿里云EndPoint
@NotBlank(message = "阿里云EndPoint不能为空" , groups = AliyunGroup.class)
private String aliyunEndPoint;
// 阿里云AccessKeyId
@NotBlank(message = "阿里云AccessKeyId不能为空" , groups = AliyunGroup.class)
private String aliyunAccessKeyId;
// 阿里云AccessKeySecret
@NotBlank(message = "阿里云AccessKeySecret不能为空" , groups = AliyunGroup.class)
private String aliyunAccessKeySecret;
// 阿里云BucketName
@NotBlank(message = "阿里云BucketName不能为空" , groups = AliyunGroup.class)
private String aliyunBucketName;
// 腾讯云绑定的域名
@NotBlank(message = "腾讯云绑定的域名不能为空" , groups = QcloudGroup.class)
@URL(message = "腾讯云绑定的域名格式不正确" , groups = QcloudGroup.class)
private String qcloudDomain;
// 腾讯云路径前缀
private String qcloudPrefix;
// 腾讯云AppId
@NotNull(message = "腾讯云AppId不能为空" , groups = QcloudGroup.class)
private Integer qcloudAppId;
// 腾讯云SecretId
@NotBlank(message = "腾讯云SecretId不能为空" , groups = QcloudGroup.class)
private String qcloudSecretId;
// 腾讯云SecretKey
@NotBlank(message = "腾讯云SecretKey不能为空" , groups = QcloudGroup.class)
private String qcloudSecretKey;
// 腾讯云BucketName
@NotBlank(message = "腾讯云BucketName不能为空" , groups = QcloudGroup.class)
private String qcloudBucketName;
// 腾讯云COS所属地区
@NotBlank(message = "所属地区不能为空" , groups = QcloudGroup.class)
private String qcloudRegion;
}
package com.hjl.cloud.valdator;
/**
* 阿里云
*/
public interface AliyunGroup {
}
package com.hjl.cloud.valdator;
/**
* 腾讯云
*/
public interface QcloudGroup {
}
package com.hjl.cloud.valdator;
/**
* 七牛
*/
public interface QiniuGroup {
}
8.测试
@PostMapping("/upload")
public String upload(MultipartFile[] file){
String imageUrl = "";
try {
for (MultipartFile mf: file) {
if (mf.isEmpty()) {
throw new OssException("上传文件不能为空");
}
String fileName = mf.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
CloudStorageService storage = OSSFactory.build();
imageUrl = storage.uploadSuffix(mf.getBytes(), suffix);
}
} catch (Exception e) {
e.printStackTrace();
}
return imageUrl ;
}
最后
以上就是知性小虾米为你收集整理的文件上传云存储(阿里云、腾讯云、七牛工具类)的全部内容,希望文章能够帮你解决文件上传云存储(阿里云、腾讯云、七牛工具类)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复