This commit is contained in:
清晨
2025-04-08 16:37:17 +08:00
commit 0c9d340a05
1659 changed files with 170293 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi-base-support</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.7.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-oss</artifactId>
<properties>
<!-- 阿里云SDK -->
<aliyun.oss.version>2.5.0</aliyun.oss.version>
<!-- 七牛云存储 -->
<qiniu.oss.version>7.1.3</qiniu.oss.version>
<!-- 腾讯云COS -->
<qcloud.cos.version>3.3</qcloud.cos.version>
<!-- 文件上传 -->
<commons-fileupload.version>1.3.3</commons-fileupload.version>
</properties>
<dependencies>
<!-- 七牛云存储-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>${qiniu.oss.version}</version>
</dependency>
<!-- 阿里云OSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<!-- 腾讯云COS https://www.qcloud.com/document/product/430/5944#.E8.8E.B7.E5.8F.96.E7.9B.AE.E5.BD.95.E5.88.97.E8.A1.A8-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>${qcloud.cos.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- dwr文件上传需要commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,367 @@
package com.ruoyi.oss;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PropertiesUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.oss.client.IOSSClient;
import com.ruoyi.oss.client.OSSClientFactory;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.oss.constant.Constants;
import com.ruoyi.oss.exception.FileNameLengthLimitExceededException;
import com.ruoyi.oss.exception.InvalidExtensionException;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
/**
* 文件上传操作助手
*/
public class OSSUploadHelper {
public static final String DEFAULT_CONFIG_FILE = "upload.properties";
// 默认的文件名最大长度
public static final int DEFAULT_FILE_NAME_LENGTH = 200;
public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = {"swf", "flv"};
public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb"};
// 默认上传的地址
private static final String DEFAULT_BASE_DIR = "upload";
private String ossBaseDir = DEFAULT_BASE_DIR;
//文件大小限制
// 默认大小 50M
public static final long DEFAULT_MAX_SIZE = 52428800;
private long maxSize = DEFAULT_MAX_SIZE;
private boolean needDatePath = false;
//允许扩展名
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
// 图片
"bmp", "gif", "jpg", "jpeg", "png",
// word excel powerpoint
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
// 压缩文件
"rar", "zip", "gz", "bz2",
// pdf
"pdf"};
public String[] allowedExtension = DEFAULT_ALLOWED_EXTENSION;
//OSS上传客户端
private String clientType = Constants.CLIENT_LOCAL;
private IOSSClient ossClient;
public void init() {
init(DEFAULT_CONFIG_FILE);
}
public void init(String configname) {
PropertiesUtil propertiesUtil = new PropertiesUtil(configname);
maxSize = propertiesUtil.getLong("upload.max.size");
ossBaseDir = propertiesUtil.getString("upload.base.dir");
String extension = propertiesUtil.getString("upload.allowed.extension");
allowedExtension = extension.split(",");
clientType = propertiesUtil.getString("upload.client.type");
this.ossClient = OSSClientFactory.build(clientType);
this.ossClient.init();
}
public void init(OssConfig ossConfig) {
maxSize = ossConfig.getMaxSize();
ossBaseDir = ossConfig.getBaseDir();
needDatePath = ossConfig.isNeedDatePath();
String extension = ossConfig.getAllowedExtension();
allowedExtension = extension.split(",");
clientType = ossConfig.getClientType();
this.ossClient = OSSClientFactory.build(clientType);
this.ossClient.init(ossConfig);
}
/**
* 以默认配置进行文件上传
*
* @param request 当前请求
* @param file 上传的文件
* 添加出错信息
* @return
* @throws IOException
* @throws FileNameLengthLimitExceededException
* @throws InvalidExtensionException
* @throws FileSizeLimitExceededException
*/
public String upload(HttpServletRequest request, MultipartFile file, String baseDir)
throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
IOException {
return upload(request, file, baseDir, allowedExtension);
}
/**
* 以默认配置进行文件上传
*
* @param request 当前请求
* @param file 上传的文件
* 添加出错信息
* @param allowedExtension 允许上传的文件类型
* @return
* @throws IOException
* @throws FileNameLengthLimitExceededException
* @throws InvalidExtensionException
* @throws FileSizeLimitExceededException
*/
public String upload(HttpServletRequest request, MultipartFile file, String baseDir, String[] allowedExtension)
throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
IOException {
return upload(request, file, baseDir, allowedExtension, maxSize, needDatePath);
}
/**
* 文件上传
*
* @param request 当前请求 从请求中提取 应用上下文根
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param allowedExtension 允许的文件类型 null 表示允许所有
* @param maxSize 最大上传的大小 -1 表示不限制
* @param needDatePath 是否需要日期目录和随机文件名前缀
* @return 返回上传成功的文件名
* @throws InvalidExtensionException 如果MIME类型不允许
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
*/
public String upload(HttpServletRequest request, MultipartFile file, String baseDir,
String[] allowedExtension, long maxSize, boolean needDatePath)
throws InvalidExtensionException, FileSizeLimitExceededException, IOException,
FileNameLengthLimitExceededException {
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > OSSUploadHelper.DEFAULT_FILE_NAME_LENGTH) {
throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNamelength,
OSSUploadHelper.DEFAULT_FILE_NAME_LENGTH);
}
assertAllowed(file, allowedExtension, maxSize);
String filename = extractFilename(file, baseDir, needDatePath);
filename = StringUtils.trimDiagonal(filename);
return ossClient.upload(file.getInputStream(), filename);
}
/**
* 以默认配置进行文件上传
*
* @param request 当前请求
* @param remoteUrl 上传的文件
* 添加出错信息
* @return
* @throws IOException
* @throws FileNameLengthLimitExceededException
* @throws InvalidExtensionException
* @throws FileSizeLimitExceededException
*/
public String remote(HttpServletRequest request, String remoteUrl, String baseDir)
throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
IOException {
return remote(request, remoteUrl, baseDir, allowedExtension);
}
/**
* 以默认配置进行文件上传
*
* @param request 当前请求
* @param remoteUrl 上传的文件
* 添加出错信息
* @param allowedExtension 允许上传的文件类型
* @return
* @throws IOException
* @throws FileNameLengthLimitExceededException
* @throws InvalidExtensionException
* @throws FileSizeLimitExceededException
*/
public String remote(HttpServletRequest request, String remoteUrl, String baseDir, String[] allowedExtension)
throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException,
IOException {
return remote(request, remoteUrl, baseDir, allowedExtension, maxSize, true);
}
/**
* 文件上传
*
* @param request 当前请求 从请求中提取 应用上下文根
* @param baseDir 相对应用的基目录
* @param remoteUrl 上传的文件
* @param allowedExtension 允许的文件类型 null 表示允许所有
* @param maxSize 最大上传的大小 -1 表示不限制
* @param needDatePathAndRandomName 是否需要日期目录和随机文件名前缀
* @return 返回上传成功的文件名
* @throws InvalidExtensionException 如果MIME类型不允许
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
*/
public String remote(HttpServletRequest request, String remoteUrl, String baseDir,
String[] allowedExtension, long maxSize, boolean needDatePathAndRandomName)
throws InvalidExtensionException, FileSizeLimitExceededException, IOException,
FileNameLengthLimitExceededException {
URL url = new URL(remoteUrl);
assertAllowed(remoteUrl, allowedExtension, maxSize);
String filename = extractFilename(remoteUrl, baseDir, needDatePathAndRandomName);
filename = StringUtils.trimDiagonal(filename);
return ossClient.upload(url.openStream(), filename);
}
public String extractFilename(String remoteUrl, String baseDir, boolean needDatePathAndRandomName)
throws UnsupportedEncodingException {
//字符串处理
if (!StringUtils.isEmpty(this.ossBaseDir)) {
if (!StringUtils.isEmpty(baseDir)) {
baseDir = this.ossBaseDir + "/" + baseDir;
} else {
baseDir = this.ossBaseDir;
}
}
String filename = remoteUrl;
int slashIndex = filename.indexOf("/");
if (slashIndex >= 0) {
filename = filename.substring(slashIndex + 1);
}
if (needDatePathAndRandomName) {
filename = datePath() + "/" + System.currentTimeMillis() + "."
+ FileUtils.getExtensionName(filename);
}
if (!StringUtils.isEmpty(baseDir)) {
filename = baseDir + "/" + filename;
}
return filename;
}
/**
* 是否允许文件上传
*
* @param remoteUrl 上传的文件
* @param allowedExtension 文件类型 null 表示允许所有
* @param maxSize 最大大小 字节为单位 -1表示不限制
* @return
* @throws InvalidExtensionException 如果MIME类型不允许
* @throws FileSizeLimitExceededException 如果超出最大大小
*/
public void assertAllowed(String remoteUrl, String[] allowedExtension, long maxSize)
throws InvalidExtensionException, FileSizeLimitExceededException {
String extension = FilenameUtils.getExtension(remoteUrl);
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
if (allowedExtension == IMAGE_EXTENSION) {
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
remoteUrl);
} else if (allowedExtension == FLASH_EXTENSION) {
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
remoteUrl);
} else if (allowedExtension == MEDIA_EXTENSION) {
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
remoteUrl);
} else {
throw new InvalidExtensionException(allowedExtension, extension, remoteUrl);
}
}
}
public String extractFilename(MultipartFile file, String baseDir, boolean needDatePathAndRandomName)
throws UnsupportedEncodingException {
if (!StringUtils.isEmpty(this.ossBaseDir)) {
if (!StringUtils.isEmpty(baseDir)) {
baseDir = this.ossBaseDir + "/" + baseDir;
} else {
baseDir = this.ossBaseDir;
}
}
String filename = file.getOriginalFilename();
//文件名必须重新命名,以时间精确到毫秒命名
filename = DateUtils.dateTimeNow() + "."
+ FileUtils.getExtensionName(filename);
if (needDatePathAndRandomName) {
filename = datePath() + "/" + filename;
}
if (!StringUtils.isEmpty(baseDir)) {
filename = baseDir + "/" + filename;
}
return filename;
}
/**
* 日期路径 即年/月/日 如2013/01/03
*
* @return
*/
private String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 是否允许文件上传
*
* @param file 上传的文件
* @param allowedExtension 文件类型 null 表示允许所有
* @param maxSize 最大大小 字节为单位 -1表示不限制
* @return
* @throws InvalidExtensionException 如果MIME类型不允许
* @throws FileSizeLimitExceededException 如果超出最大大小
*/
public void assertAllowed(MultipartFile file, String[] allowedExtension, long maxSize)
throws InvalidExtensionException, FileSizeLimitExceededException {
String filename = file.getOriginalFilename();
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
if (allowedExtension == IMAGE_EXTENSION) {
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
filename);
} else if (allowedExtension == FLASH_EXTENSION) {
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
filename);
} else if (allowedExtension == MEDIA_EXTENSION) {
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
filename);
} else {
throw new InvalidExtensionException(allowedExtension, extension, filename);
}
}
long size = file.getSize();
if (maxSize != -1 && size > maxSize) {
throw new FileSizeLimitExceededException("not allowed upload upload", size, maxSize);
}
}
/**
* 判断MIME类型是否是允许的MIME类型
*
* @param extension
* @param allowedExtension
* @return
*/
public boolean isAllowedExtension(String extension, String[] allowedExtension) {
for (String str : allowedExtension) {
if (str.trim().equalsIgnoreCase(extension.trim())) {
return true;
}
}
return false;
}
public void delete(HttpServletRequest request, String filename) throws IOException {
if (StringUtils.isEmpty(filename)) {
return;
}
ossClient.delete(filename);
}
}

View File

@@ -0,0 +1,13 @@
package com.ruoyi.oss.client;
/**
* All rights Reserved, Designed By kjt.gzst.gov.cn
*
* @version V1.0
* @title: IOSSClient.java
* @description: 操作客户端虚类 * @date: 2017年8月11日 下午9:55:00
* @copyright: 2017 kjt.gzst.gov.cn Inc. All rights reserved.
*/
public abstract class AbstractOSSClient implements IOSSClient {
//protected abstract void init();
}

View File

@@ -0,0 +1,97 @@
package com.ruoyi.oss.client;
import com.aliyun.oss.OSSClient;
import com.ruoyi.common.utils.PropertiesUtil;
import com.ruoyi.oss.config.AliyunConfig;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.oss.exception.OSSException;
import java.io.InputStream;
/**
* All rights Reserved, Designed By kjt.gzst.gov.cn
*
* @version V1.0
* @title: IOSSClient.java
* @description: 阿里云的客户端操作 * @date: 2017年8月11日 下午9:55:00
* @copyright: 2017 kjt.gzst.gov.cn Inc. All rights reserved.
*/
public class AliyunOSSClient extends AbstractOSSClient {
public static final String DEFAULT_CONFIG_FILE = "aliyun.oss.properties";
//阿里云客户端
private OSSClient client;
//阿里云API的内或外网域名
private String endpoint;
//阿里云API的密钥Access Key ID
private String accessKeyId;
//阿里云API的密钥Access Key Secret
private String accessKeySecret;
//访问域名
private String domain;
//bucket名称
private String bucketName;
@Override
public void init() {
init(DEFAULT_CONFIG_FILE);
}
@Override
public void init(String propertiesName) {
PropertiesUtil p = new PropertiesUtil(propertiesName);
endpoint = p.getString("aliyun.oss.endpoint");
accessKeyId = p.getString("aliyun.oss.access-key-id");
accessKeySecret = p.getString("aliyun.oss.access-key-secret");
bucketName = p.getString("aliyun.oss.bucket-name");
domain = p.getString("aliyun.oss.domain");
client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
@Override
public void init(OssConfig config) {
AliyunConfig aliyunConfig = config.getAliyun();
endpoint = aliyunConfig.getEndpoint();
accessKeyId = aliyunConfig.getAccessKeyId();
accessKeySecret = aliyunConfig.getAccessKeySecret();
bucketName = aliyunConfig.getBucketName();
domain = aliyunConfig.getDomain();
client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 一般不推荐使用
*
* @return
*/
public OSSClient getClient() {
return this.client;
}
/**
* 文件上传
*
* @param inputStream
* @param path
* @return
*/
@Override
public String upload(InputStream inputStream, String path) {
try {
client.putObject(bucketName, path, inputStream);
} catch (Exception e) {
throw new OSSException("上传文件失败", e);
}
return domain + "/" + path;
}
@Override
public void delete(String filename) {
try {
filename = filename.replace(domain + "/", "");
client.deleteObject(bucketName, filename);
} catch (Exception e) {
throw new OSSException("删除文件失败", e);
}
}
}

View File

@@ -0,0 +1,55 @@
package com.ruoyi.oss.client;
import com.ruoyi.oss.config.OssConfig;
import java.io.InputStream;
/**
* All rights Reserved, Designed By kjt.gzst.gov.cn
*
* @version V1.0
* @title: IOSSClient.java
* @description: 常量 * @date: 2017年8月11日 下午9:55:00
* @copyright: 2017 kjt.gzst.gov.cn Inc. All rights reserved.
*/
//接口:插入、刪除、修改
//文件HTTP直接上传
//用一个虚类来处理公用的
//一个配置的地方,本系统默认采用阿里云,也就是云上贵州
public interface IOSSClient {
/**
* 客户端初始化
*/
void init();
/**
* 客户端初始化
*
* @param propertiesName
*/
void init(String propertiesName);
/**
* 客户端初始化
*
* @param config
*/
void init(OssConfig config);
/**
* 文件上传
*
* @param inputStream
* @param path
* @return 返回可以访问的路径
*/
String upload(InputStream inputStream, String path);
/**
* 删除文件
*
* @param filename 文件的路径
*/
void delete(String filename);
}

View File

@@ -0,0 +1,94 @@
package com.ruoyi.oss.client;
import com.ruoyi.common.utils.PropertiesUtil;
import com.ruoyi.oss.config.LocalConfig;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.oss.exception.OSSException;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* All rights Reserved, Designed By kjt.gzst.gov.cn
*
* @version V1.0
* @title: IOSSClient.java
* @description: 这里为本地操作 * @date: 2017年8月11日 下午9:55:00
* @copyright: 2017 kjt.gzst.gov.cn Inc. All rights reserved.
*/
public class LocalClient extends AbstractOSSClient {
public static final String DEFAULT_CONFIG_FILE = "local.properties";
private String domain;//本地域名配置
private String uploadFilePath;//上传路径
@Override
public void init() {
init(DEFAULT_CONFIG_FILE);
}
@Override
public void init(String propertiesName) {
PropertiesUtil p = new PropertiesUtil(propertiesName);
domain = p.getString("local.domain");
uploadFilePath = p.getString("local.upload-file-path");
}
@Override
public void init(OssConfig config) {
LocalConfig localConfig = config.getLocal();
domain = localConfig.getDomain();
uploadFilePath = localConfig.getUploadFilePath();
}
/**
* 判断文件地址保存文件
*
* @param path
* @return
* @throws IOException
*/
private File getAbsoluteFile(String path) throws IOException {
String basePath = uploadFilePath;
File desc = new File(basePath + File.separator + path);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
if (!desc.exists()) {
desc.createNewFile();
}
return desc;
}
/**
* 文件上传
*
* @param inputStream
* @param path
* @return
*/
@Override
public String upload(InputStream inputStream, String path) {
try {
File outFile = getAbsoluteFile(path);
FileUtils.copyInputStreamToFile(inputStream, outFile);
} catch (Exception e) {
throw new OSSException("上传文件失败", e);
}
return domain + "/" + path;
}
@Override
public void delete(String filename) {
String basePath = uploadFilePath;
File desc = new File(basePath + File.pathSeparator + filename);
if (desc.exists()) {
desc.delete();
}
}
}

View File

@@ -0,0 +1,22 @@
package com.ruoyi.oss.client;
import com.ruoyi.oss.constant.Constants;
/**
* 文件上传Factory
*/
public final class OSSClientFactory {
public static IOSSClient build(String clientType) {
IOSSClient ossClient;
if (Constants.CLIENT_LOCAL.equals(clientType)) {
ossClient = new LocalClient();
} else if (Constants.CLIENTA_ALIYUN.equals(clientType)) {
ossClient = new AliyunOSSClient();
} else {
return null;
}
return ossClient;
}
}

View File

@@ -0,0 +1,62 @@
package com.ruoyi.oss.client;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.oss.exception.OSSException;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class QiniuOSSClient extends AbstractOSSClient {
private UploadManager uploadManager;
private String token;
//访问域名
private String domain;
@Override
public void init() {
}
@Override
public void init(String propertiesName) {
}
@Override
public void init(OssConfig config) {
}
@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("上传文件失败", e);
}
}
private 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 domain + "/" + path;
}
@Override
public void delete(String filename) {
}
}

View File

@@ -0,0 +1,66 @@
package com.ruoyi.oss.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* All rights Reserved, Designed By www.sunseagear.com
*
* @version V1.0
* @package com.ruoyi.oss.config
* @title:
* @description: 阿里云配置 * @date: 2018/4/26 9:39
* @copyright: 2017 www.sunseagear.com Inc. All rights reserved.
*/
@ConfigurationProperties(prefix = "oss")
public class AliyunConfig {
//阿里云api的内或外网域名
String endpoint = "";
//阿里云api的密钥access key id
String accessKeyId = "";
//阿里云api的密钥access key secret
String accessKeySecret = "";
//阿里云api的bucket名称
String bucketName = "";
//外部访问域名
String domain = "";
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}

View File

@@ -0,0 +1,36 @@
package com.ruoyi.oss.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* All rights Reserved, Designed By www.sunseagear.com
*
* @version V1.0
* @package com.ruoyi.oss.config
* @title:
* @description: 阿里云配置 * @date: 2018/4/26 9:39
* @copyright: 2017 www.sunseagear.com Inc. All rights reserved.
*/
@ConfigurationProperties(prefix = "oss")
public class LocalConfig {
//外部访问域名
String domain = "";
//上传路径
String uploadFilePath = "";
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getUploadFilePath() {
return uploadFilePath;
}
public void setUploadFilePath(String uploadFilePath) {
this.uploadFilePath = uploadFilePath;
}
}

View File

@@ -0,0 +1,88 @@
package com.ruoyi.oss.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* All rights Reserved, Designed By www.sunseagear.com
*
* @version V1.0
* @package com.ruoyi.oss.config
* @title:
* @description: OSS配置 * @date: 2018/4/26 9:43
* @copyright: 2017 www.sunseagear.com Inc. All rights reserved.
*/
@ConfigurationProperties(prefix = "oss")
public class OssConfig {
//使用的上传存储空间,local本地,aliyun:阿里云
String clientType = "";
//默认上传目录
String baseDir = "";
//允许的文件扩展名
String allowedExtension = "";
//最大文件大小 50M
long maxSize = 52428800;
//是否需要按照日期存放文件
boolean needDatePath = false;
;
private AliyunConfig aliyun;
private LocalConfig local;
public AliyunConfig getAliyun() {
return aliyun;
}
public void setAliyun(AliyunConfig aliyun) {
this.aliyun = aliyun;
}
public LocalConfig getLocal() {
return local;
}
public void setLocal(LocalConfig local) {
this.local = local;
}
public String getClientType() {
return clientType;
}
public void setClientType(String clientType) {
this.clientType = clientType;
}
public String getBaseDir() {
return baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
public String getAllowedExtension() {
return allowedExtension;
}
public void setAllowedExtension(String allowedExtension) {
this.allowedExtension = allowedExtension;
}
public long getMaxSize() {
return maxSize;
}
public void setMaxSize(long maxSize) {
this.maxSize = maxSize;
}
public boolean isNeedDatePath() {
return needDatePath;
}
public void setNeedDatePath(boolean needDatePath) {
this.needDatePath = needDatePath;
}
}

View File

@@ -0,0 +1,6 @@
package com.ruoyi.oss.constant;
public interface Constants {
String CLIENT_LOCAL = "local"; //本地
String CLIENTA_ALIYUN = "aliyun"; //本地
}

View File

@@ -0,0 +1,38 @@
package com.ruoyi.oss.exception;
import org.apache.commons.fileupload.FileUploadException;
/**
* 文件名超长
* <p>User: Zhang Kaitao
* <p>Date: 13-3-8 下午8:44
* <p>Version: 1.0
*/
@SuppressWarnings("serial")
public class FileNameLengthLimitExceededException extends FileUploadException {
private int length;
private int maxLength;
private String filename;
public FileNameLengthLimitExceededException(String filename, int length, int maxLength) {
super("file name : [" + filename + "], length : [" + length + "], max length : [" + maxLength + "]");
this.length = length;
this.maxLength = maxLength;
this.filename = filename;
}
public String getFilename() {
return filename;
}
public int getLength() {
return length;
}
public int getMaxLength() {
return maxLength;
}
}

View File

@@ -0,0 +1,55 @@
package com.ruoyi.oss.exception;
import org.apache.commons.fileupload.FileUploadException;
import java.util.Arrays;
/**
*
*/
@SuppressWarnings("serial")
public class InvalidExtensionException extends FileUploadException {
private String[] allowedExtension;
private String extension;
private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename) {
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : ["
+ Arrays.toString(allowedExtension) + "]");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
public String[] getAllowedExtension() {
return allowedExtension;
}
public String getExtension() {
return extension;
}
public String getFilename() {
return filename;
}
public static class InvalidImageExtensionException extends InvalidExtensionException {
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidFlashExtensionException extends InvalidExtensionException {
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException {
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
}

View File

@@ -0,0 +1,33 @@
package com.ruoyi.oss.exception;
/**
* OSS异常
* Created by 王存见 on 2017/8/11.
*/
public class OSSException extends RuntimeException {
public OSSException() {
super();
}
public OSSException(String message) {
super(message);
}
public OSSException(String message, Throwable cause) {
super(message, cause);
}
public OSSException(Throwable cause) {
super(cause);
}
protected OSSException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,162 @@
package com.ruoyi.oss.utils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.utils.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class AliyunOSSClientUtil {
public static final String DEFAULT_CONFIG_FILE = "aliyun.oss.properties";
//log
private static final Logger LOG = LoggerFactory.getLogger(AliyunOSSClientUtil.class);
//阿里云API的内或外网域名
private static String ENDPOINT;
//阿里云API的密钥Access Key ID
private static String ACCESS_KEY_ID;
//阿里云API的密钥Access Key Secret
private static String ACCESS_KEY_SECRET;
//init static datas
static {
PropertiesUtil p = new PropertiesUtil(DEFAULT_CONFIG_FILE);
ENDPOINT = p.getString("aliyun.oss.endpoint");
ACCESS_KEY_ID = p.getString("aliyun.oss.access_key_id");
ACCESS_KEY_SECRET = p.getString("aliyun.oss.access_key_secret");
}
/**
* 获取阿里云OSS客户端对象
*/
public static final OSSClient getOSSClient() {
return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
* 新建Bucket --Bucket权限:私有
*
* @param bucketName bucket名称
* @return true 新建Bucket成功
*/
public static final boolean createBucket(OSSClient client, String bucketName) {
Bucket bucket = client.createBucket(bucketName);
return bucketName.equals(bucket.getName());
}
/**
* 删除Bucket
*
* @param bucketName bucket名称
*/
public static final void deleteBucket(OSSClient client, String bucketName) {
client.deleteBucket(bucketName);
LOG.info("删除" + bucketName + "Bucket成功");
}
/**
* 向阿里云的OSS存储中存储文件 --file也可以用InputStream替代
*
* @param client OSS客户端
* @param file 上传文件
* @param bucketName bucket名称
* @param diskName 上传文件的目录 --bucket下文件的路径
* @return String 唯一MD5数字签名
*/
public static final String uploadObject2OSS(OSSClient client, File file, String bucketName, String diskName) {
String resultStr = null;
try {
InputStream is = new FileInputStream(file);
String fileName = file.getName();
Long fileSize = file.length();
//创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(is.available());
metadata.setCacheControl("no-cache");
metadata.setHeader("Pragma", "no-cache");
metadata.setContentEncoding("utf-8");
metadata.setContentType(getContentType(fileName));
metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
//上传文件
PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
//解析结果
resultStr = putResult.getETag();
} catch (Exception e) {
LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
}
return resultStr;
}
/**
* 根据key获取OSS服务器上的文件输入流
*
* @param client OSS客户端
* @param bucketName bucket名称
* @param diskName 文件路径
* @param key Bucket下的文件的路径名+文件名
*/
public static final InputStream getOSS2InputStream(OSSClient client, String bucketName, String diskName, String key) {
OSSObject ossObj = client.getObject(bucketName, diskName + key);
return ossObj.getObjectContent();
}
/**
* 根据key删除OSS服务器上的文件
*
* @param client OSS客户端
* @param bucketName bucket名称
* @param diskName 文件路径
* @param key Bucket下的文件的路径名+文件名
*/
public static void deleteFile(OSSClient client, String bucketName, String diskName, String key) {
client.deleteObject(bucketName, diskName + key);
LOG.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
*
* @param fileName 文件名
* @return 文件的contentType
*/
public static final String getContentType(String fileName) {
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if ("bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if ("gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if ("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension) || "png".equalsIgnoreCase(fileExtension)) {
return "image/jpeg";
}
if ("html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if ("txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if ("vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if ("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if ("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if ("xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
return "text/html";
}
}

View File

@@ -0,0 +1,61 @@
package com.ruoyi.oss.utils;
import com.ruoyi.oss.OSSUploadHelper;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.oss.exception.FileNameLengthLimitExceededException;
import com.ruoyi.oss.exception.InvalidExtensionException;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* All rights Reserved, Designed By www.sunseagear.com
*
* @version V1.0
* @package com.sunseagear.oss.controller
* @title: 附件上传助手
* @description: 附件上传助手 * @date: 2018-04-25 14:25:55
* @copyright: 2018 www.sunseagear.com Inc. All rights reserved.
*/
@Component("attachmentHelper")
@EnableConfigurationProperties({OssConfig.class})
public class AttachmentHelper {
@Autowired
private OssConfig ossConfig;
private OSSUploadHelper uploadHelper;
@PostConstruct
public void initHelper() {
uploadHelper = new OSSUploadHelper();
uploadHelper.init(ossConfig);
}
public String upload(HttpServletRequest request, MultipartFile file) throws FileSizeLimitExceededException,
IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
String basePath = request.getParameter("directory");
return upload(request, file, basePath);
}
public String upload(HttpServletRequest request, MultipartFile file, String directory) throws FileSizeLimitExceededException,
IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
String url = uploadHelper.upload(request, file, directory);
return url;
}
public String remote(HttpServletRequest request, String remoteUrl) throws FileSizeLimitExceededException,
IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
String basePath = request.getParameter("base_path");
String url = uploadHelper.remote(request, remoteUrl, basePath);
return url;
}
}