【修改】CommonController修改上传与下载文件接口
This commit is contained in:
+210
-171
@@ -1,172 +1,211 @@
|
||||
package com.jero.common.util;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.pinyin.PinyinUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import com.jero.common.constant.DataBaseConstant;
|
||||
import com.jero.common.exception.JeroBootException;
|
||||
import com.jero.common.util.oss.OssBootUtil;
|
||||
import org.jeecgframework.poi.util.PoiPublicUtil;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
public class CommonUtils {
|
||||
|
||||
//中文正则
|
||||
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
|
||||
|
||||
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
|
||||
String dbPath = null;
|
||||
String fileName = "image" + Math.round(Math.random() * 100000000000L);
|
||||
fileName += "." + PoiPublicUtil.getFileExtendName(data);
|
||||
try {
|
||||
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
|
||||
File file = new File(basePath + File.separator + bizPath + File.separator );
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();// 创建文件根目录
|
||||
}
|
||||
String savePath = file.getPath() + File.separator + fileName;
|
||||
File savefile = new File(savePath);
|
||||
FileCopyUtils.copy(data, savefile);
|
||||
dbPath = bizPath + File.separator + fileName;
|
||||
}else {
|
||||
InputStream in = new ByteArrayInputStream(data);
|
||||
String relativePath = bizPath+"/"+fileName;
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
dbPath = MinioUtil.upload(in,relativePath);
|
||||
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
|
||||
dbPath = OssBootUtil.upload(in,relativePath);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return dbPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件名是否带盘符,重新处理
|
||||
* @param fileName
|
||||
* @return
|
||||
*/
|
||||
public static String getFileName(String fileName){
|
||||
//判断是否带有盘符信息
|
||||
// Check for Unix-style path
|
||||
int unixSep = fileName.lastIndexOf('/');
|
||||
// Check for Windows-style path
|
||||
int winSep = fileName.lastIndexOf('\\');
|
||||
// Cut off at latest possible point
|
||||
int pos = (winSep > unixSep ? winSep : unixSep);
|
||||
if (pos != -1) {
|
||||
// Any sort of path separator found...
|
||||
fileName = fileName.substring(pos + 1);
|
||||
}
|
||||
//替换上传文件名字的特殊字符
|
||||
fileName = fileName.replace("=","").replace(",","").replace("&","").replace("#", "");
|
||||
//替换上传文件名字中的空格
|
||||
fileName=fileName.replaceAll("\\s","");
|
||||
return fileName;
|
||||
}
|
||||
|
||||
// java 判断字符串里是否包含中文字符
|
||||
public static boolean ifContainChinese(String str) {
|
||||
if(str.getBytes().length == str.length()){
|
||||
return false;
|
||||
}else{
|
||||
Matcher m = ZHONGWEN_PATTERN.matcher(str);
|
||||
if (m.find()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一全局上传
|
||||
* @Return: java.lang.String
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String uploadType) {
|
||||
String url = "";
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
url = MinioUtil.upload(file,bizPath);
|
||||
}else{
|
||||
url = OssBootUtil.upload(file,bizPath);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一全局上传 带桶
|
||||
* @Return: java.lang.String
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
|
||||
String url = "";
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
url = MinioUtil.upload(file,bizPath,customBucket);
|
||||
}else{
|
||||
url = OssBootUtil.upload(file,bizPath,customBucket);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/** 当前系统数据库类型 */
|
||||
private static String DB_TYPE = "";
|
||||
public static String getDatabaseType() {
|
||||
if(oConvertUtils.isNotEmpty(DB_TYPE)){
|
||||
return DB_TYPE;
|
||||
}
|
||||
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
|
||||
try {
|
||||
return getDatabaseTypeByDataSource(dataSource);
|
||||
} catch (SQLException e) {
|
||||
//e.printStackTrace();
|
||||
log.warn(e.getMessage());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库类型
|
||||
* @param dataSource
|
||||
* @return
|
||||
* @throws SQLException
|
||||
*/
|
||||
private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
|
||||
if("".equals(DB_TYPE)) {
|
||||
Connection connection = dataSource.getConnection();
|
||||
try {
|
||||
DatabaseMetaData md = connection.getMetaData();
|
||||
String dbType = md.getDatabaseProductName().toLowerCase();
|
||||
if(dbType.indexOf("mysql")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
|
||||
}else if(dbType.indexOf("oracle")>=0 ||dbType.indexOf("dm")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
|
||||
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
|
||||
}else if(dbType.indexOf("postgresql")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
|
||||
}else {
|
||||
throw new JeroBootException("数据库类型:["+dbType+"]不识别!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}finally {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
return DB_TYPE;
|
||||
|
||||
}
|
||||
package com.jero.common.util;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.pinyin.PinyinUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import com.jero.common.constant.DataBaseConstant;
|
||||
import com.jero.common.exception.JeroBootException;
|
||||
import com.jero.common.util.oss.OssBootUtil;
|
||||
import org.jeecgframework.poi.util.PoiPublicUtil;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
public class CommonUtils {
|
||||
|
||||
//中文正则
|
||||
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
|
||||
|
||||
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
|
||||
String dbPath = null;
|
||||
String fileName = "image" + Math.round(Math.random() * 100000000000L);
|
||||
fileName += "." + PoiPublicUtil.getFileExtendName(data);
|
||||
try {
|
||||
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
|
||||
File file = new File(basePath + File.separator + bizPath + File.separator );
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();// 创建文件根目录
|
||||
}
|
||||
String savePath = file.getPath() + File.separator + fileName;
|
||||
File savefile = new File(savePath);
|
||||
FileCopyUtils.copy(data, savefile);
|
||||
dbPath = bizPath + File.separator + fileName;
|
||||
}else {
|
||||
InputStream in = new ByteArrayInputStream(data);
|
||||
String relativePath = bizPath+"/"+fileName;
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
dbPath = MinioUtil.upload(in,relativePath);
|
||||
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
|
||||
dbPath = OssBootUtil.upload(in,relativePath);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return dbPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件名是否带盘符,重新处理
|
||||
* @param fileName
|
||||
* @return
|
||||
*/
|
||||
public static String getFileName(String fileName){
|
||||
//判断是否带有盘符信息
|
||||
// Check for Unix-style path
|
||||
int unixSep = fileName.lastIndexOf('/');
|
||||
// Check for Windows-style path
|
||||
int winSep = fileName.lastIndexOf('\\');
|
||||
// Cut off at latest possible point
|
||||
int pos = (winSep > unixSep ? winSep : unixSep);
|
||||
if (pos != -1) {
|
||||
// Any sort of path separator found...
|
||||
fileName = fileName.substring(pos + 1);
|
||||
}
|
||||
//替换上传文件名字的特殊字符
|
||||
fileName = fileName.replace("=","").replace(",","").replace("&","").replace("#", "");
|
||||
//替换上传文件名字中的空格
|
||||
fileName=fileName.replaceAll("\\s","");
|
||||
return fileName;
|
||||
}
|
||||
|
||||
// java 判断字符串里是否包含中文字符
|
||||
public static boolean ifContainChinese(String str) {
|
||||
if(str.getBytes().length == str.length()){
|
||||
return false;
|
||||
}else{
|
||||
Matcher m = ZHONGWEN_PATTERN.matcher(str);
|
||||
if (m.find()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一全局上传
|
||||
* @Return: java.lang.String
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String uploadType) {
|
||||
String url = "";
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
url = MinioUtil.upload(file,bizPath);
|
||||
}else{
|
||||
url = OssBootUtil.upload(file,bizPath);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一全局上传 带桶
|
||||
* @Return: java.lang.String
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
|
||||
String url = "";
|
||||
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
url = MinioUtil.upload(file,bizPath,customBucket);
|
||||
}else{
|
||||
url = OssBootUtil.upload(file,bizPath,customBucket);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
/**
|
||||
* 本地文件上传
|
||||
* @param mf 文件
|
||||
* @param bizPath 自定义路径
|
||||
* @return
|
||||
*/
|
||||
public static String uploadLocal(MultipartFile mf,String bizPath, String uploadpath){
|
||||
try {
|
||||
String ctxPath = uploadpath;
|
||||
String fileName = null;
|
||||
File file = new File(ctxPath + File.separator + bizPath + File.separator );
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();// 创建文件根目录
|
||||
}
|
||||
String orgName = mf.getOriginalFilename();// 获取文件名
|
||||
orgName = CommonUtils.getFileName(orgName);
|
||||
if(orgName.indexOf(".")!=-1){
|
||||
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
|
||||
}else{
|
||||
fileName = orgName+ "_" + System.currentTimeMillis();
|
||||
}
|
||||
String savePath = file.getPath() + File.separator + fileName;
|
||||
File savefile = new File(savePath);
|
||||
FileCopyUtils.copy(mf.getBytes(), savefile);
|
||||
String dbpath = null;
|
||||
if(oConvertUtils.isNotEmpty(bizPath)){
|
||||
dbpath = bizPath + File.separator + fileName;
|
||||
}else{
|
||||
dbpath = fileName;
|
||||
}
|
||||
if (dbpath.contains("\\")) {
|
||||
dbpath = dbpath.replace("\\", "/");
|
||||
}
|
||||
return dbpath;
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
/** 当前系统数据库类型 */
|
||||
private static String DB_TYPE = "";
|
||||
public static String getDatabaseType() {
|
||||
if(oConvertUtils.isNotEmpty(DB_TYPE)){
|
||||
return DB_TYPE;
|
||||
}
|
||||
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
|
||||
try {
|
||||
return getDatabaseTypeByDataSource(dataSource);
|
||||
} catch (SQLException e) {
|
||||
//e.printStackTrace();
|
||||
log.warn(e.getMessage());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库类型
|
||||
* @param dataSource
|
||||
* @return
|
||||
* @throws SQLException
|
||||
*/
|
||||
private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
|
||||
if("".equals(DB_TYPE)) {
|
||||
Connection connection = dataSource.getConnection();
|
||||
try {
|
||||
DatabaseMetaData md = connection.getMetaData();
|
||||
String dbType = md.getDatabaseProductName().toLowerCase();
|
||||
if(dbType.indexOf("mysql")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
|
||||
}else if(dbType.indexOf("oracle")>=0 ||dbType.indexOf("dm")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
|
||||
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
|
||||
}else if(dbType.indexOf("postgresql")>=0) {
|
||||
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
|
||||
}else {
|
||||
throw new JeroBootException("数据库类型:["+dbType+"]不识别!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}finally {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
return DB_TYPE;
|
||||
|
||||
}
|
||||
}
|
||||
+210
-209
@@ -1,209 +1,210 @@
|
||||
package com.jero.common.util;
|
||||
|
||||
import io.minio.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.util.filter.StrAttackFilter;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
/**
|
||||
* minio文件上传工具类
|
||||
*/
|
||||
@Slf4j
|
||||
public class MinioUtil {
|
||||
private static String minioUrl;
|
||||
private static String minioName;
|
||||
private static String minioPass;
|
||||
private static String bucketName;
|
||||
|
||||
public static void setMinioUrl(String minioUrl) {
|
||||
MinioUtil.minioUrl = minioUrl;
|
||||
}
|
||||
|
||||
public static void setMinioName(String minioName) {
|
||||
MinioUtil.minioName = minioName;
|
||||
}
|
||||
|
||||
public static void setMinioPass(String minioPass) {
|
||||
MinioUtil.minioPass = minioPass;
|
||||
}
|
||||
|
||||
public static void setBucketName(String bucketName) {
|
||||
MinioUtil.bucketName = bucketName;
|
||||
}
|
||||
|
||||
public static String getMinioUrl() {
|
||||
return minioUrl;
|
||||
}
|
||||
|
||||
public static String getBucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
private static MinioClient minioClient = null;
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
* @param file
|
||||
* @return
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String customBucket) {
|
||||
String file_url = "";
|
||||
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
bizPath=StrAttackFilter.filter(bizPath);
|
||||
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
String newBucket = bucketName;
|
||||
if(oConvertUtils.isNotEmpty(customBucket)){
|
||||
newBucket = customBucket;
|
||||
}
|
||||
try {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
// 检查存储桶是否已经存在
|
||||
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
|
||||
log.info("Bucket already exists.");
|
||||
} else {
|
||||
// 创建一个名为ota的存储桶
|
||||
minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
|
||||
log.info("create a new bucket.");
|
||||
}
|
||||
InputStream stream = file.getInputStream();
|
||||
// 获取文件名
|
||||
String orgName = file.getOriginalFilename();
|
||||
if("".equals(orgName)){
|
||||
orgName=file.getName();
|
||||
}
|
||||
orgName = CommonUtils.getFileName(orgName);
|
||||
String objectName = bizPath+"/"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
|
||||
|
||||
// 使用putObject上传一个本地文件到存储桶中。
|
||||
if(objectName.startsWith("/")){
|
||||
objectName = objectName.substring(1);
|
||||
}
|
||||
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
|
||||
.bucket(newBucket)
|
||||
.contentType("application/octet-stream")
|
||||
.stream(stream,stream.available(),-1).build();
|
||||
minioClient.putObject(objectArgs);
|
||||
stream.close();
|
||||
file_url = minioUrl+newBucket+"/"+objectName;
|
||||
}catch (Exception e){
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return file_url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传
|
||||
* @param file
|
||||
* @param bizPath
|
||||
* @return
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath) {
|
||||
return upload(file,bizPath,null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件流
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @return
|
||||
*/
|
||||
public static InputStream getMinioFile(String bucketName,String objectName){
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
initMinio(minioUrl, minioName, minioPass);
|
||||
GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
|
||||
.bucket(bucketName).build();
|
||||
inputStream = minioClient.getObject(objectArgs);
|
||||
} catch (Exception e) {
|
||||
log.info("文件获取失败" + e.getMessage());
|
||||
}
|
||||
return inputStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void removeObject(String bucketName, String objectName) {
|
||||
try {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
|
||||
.bucket(bucketName).build();
|
||||
minioClient.removeObject(objectArgs);
|
||||
}catch (Exception e){
|
||||
log.info("文件删除失败" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件外链
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @param expires
|
||||
* @return
|
||||
*/
|
||||
public static String getObjectURL(String bucketName, String objectName, Integer expires) {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
try{
|
||||
GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
|
||||
.bucket(bucketName)
|
||||
.expiry(expires).build();
|
||||
String url = minioClient.getPresignedObjectUrl(objectArgs);
|
||||
return URLDecoder.decode(url,"UTF-8");
|
||||
}catch (Exception e){
|
||||
log.info("文件路径获取失败" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化客户端
|
||||
* @param minioUrl
|
||||
* @param minioName
|
||||
* @param minioPass
|
||||
* @return
|
||||
*/
|
||||
private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) {
|
||||
if (minioClient == null) {
|
||||
try {
|
||||
minioClient = MinioClient.builder()
|
||||
.endpoint(minioUrl)
|
||||
.credentials(minioName, minioPass)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return minioClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到minio
|
||||
* @param stream
|
||||
* @param relativePath
|
||||
* @return
|
||||
*/
|
||||
public static String upload(InputStream stream,String relativePath) throws Exception {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
|
||||
log.info("Bucket already exists.");
|
||||
} else {
|
||||
// 创建一个名为ota的存储桶
|
||||
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
|
||||
log.info("create a new bucket.");
|
||||
}
|
||||
PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
|
||||
.bucket(bucketName)
|
||||
.contentType("application/octet-stream")
|
||||
.stream(stream,stream.available(),-1).build();
|
||||
minioClient.putObject(objectArgs);
|
||||
stream.close();
|
||||
return minioUrl+bucketName+"/"+relativePath;
|
||||
}
|
||||
|
||||
}
|
||||
package com.jero.common.util;
|
||||
|
||||
import io.minio.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.util.filter.StrAttackFilter;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.validation.constraints.Null;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
/**
|
||||
* minio文件上传工具类
|
||||
*/
|
||||
@Slf4j
|
||||
public class MinioUtil {
|
||||
private static String minioUrl;
|
||||
private static String minioName;
|
||||
private static String minioPass;
|
||||
private static String bucketName;
|
||||
|
||||
public static void setMinioUrl(String minioUrl) {
|
||||
MinioUtil.minioUrl = minioUrl;
|
||||
}
|
||||
|
||||
public static void setMinioName(String minioName) {
|
||||
MinioUtil.minioName = minioName;
|
||||
}
|
||||
|
||||
public static void setMinioPass(String minioPass) {
|
||||
MinioUtil.minioPass = minioPass;
|
||||
}
|
||||
|
||||
public static void setBucketName(String bucketName) {
|
||||
MinioUtil.bucketName = bucketName;
|
||||
}
|
||||
|
||||
public static String getMinioUrl() {
|
||||
return minioUrl;
|
||||
}
|
||||
|
||||
public static String getBucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
private static MinioClient minioClient = null;
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
* @param file
|
||||
* @return
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String customBucket) {
|
||||
String file_url = "";
|
||||
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
bizPath=StrAttackFilter.filter(bizPath);
|
||||
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
String newBucket = bucketName;
|
||||
if(oConvertUtils.isNotEmpty(customBucket)){
|
||||
newBucket = customBucket;
|
||||
}
|
||||
try {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
// 检查存储桶是否已经存在
|
||||
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
|
||||
log.info("Bucket already exists.");
|
||||
} else {
|
||||
// 创建一个名为ota的存储桶
|
||||
minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
|
||||
log.info("create a new bucket.");
|
||||
}
|
||||
InputStream stream = file.getInputStream();
|
||||
// 获取文件名
|
||||
String orgName = file.getOriginalFilename();
|
||||
if("".equals(orgName)){
|
||||
orgName=file.getName();
|
||||
}
|
||||
orgName = CommonUtils.getFileName(orgName);
|
||||
String objectName = bizPath+"/"+orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
|
||||
|
||||
// 使用putObject上传一个本地文件到存储桶中。
|
||||
if(objectName.startsWith("/")){
|
||||
objectName = objectName.substring(1);
|
||||
}
|
||||
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
|
||||
.bucket(newBucket)
|
||||
.contentType("application/octet-stream")
|
||||
.stream(stream,stream.available(),-1).build();
|
||||
minioClient.putObject(objectArgs);
|
||||
stream.close();
|
||||
file_url = minioUrl+newBucket+"/"+objectName;
|
||||
}catch (Exception e){
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return file_url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传
|
||||
* @param file
|
||||
* @param bizPath
|
||||
* @return
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath) {
|
||||
return upload(file,bizPath,null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件流
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @return
|
||||
*/
|
||||
public static InputStream getMinioFile(String bucketName, String objectName){
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
initMinio(minioUrl, minioName, minioPass);
|
||||
GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
|
||||
.bucket(bucketName).build();
|
||||
inputStream = minioClient.getObject(objectArgs);
|
||||
} catch (Exception e) {
|
||||
log.info("文件获取失败" + e.getMessage());
|
||||
}
|
||||
return inputStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void removeObject(String bucketName, String objectName) {
|
||||
try {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
|
||||
.bucket(bucketName).build();
|
||||
minioClient.removeObject(objectArgs);
|
||||
}catch (Exception e){
|
||||
log.info("文件删除失败" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件外链
|
||||
* @param bucketName
|
||||
* @param objectName
|
||||
* @param expires
|
||||
* @return
|
||||
*/
|
||||
public static String getObjectURL(String bucketName, String objectName, Integer expires) {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
try{
|
||||
GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
|
||||
.bucket(bucketName)
|
||||
.expiry(expires).build();
|
||||
String url = minioClient.getPresignedObjectUrl(objectArgs);
|
||||
return URLDecoder.decode(url,"UTF-8");
|
||||
}catch (Exception e){
|
||||
log.info("文件路径获取失败" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化客户端
|
||||
* @param minioUrl
|
||||
* @param minioName
|
||||
* @param minioPass
|
||||
* @return
|
||||
*/
|
||||
private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) {
|
||||
if (minioClient == null) {
|
||||
try {
|
||||
minioClient = MinioClient.builder()
|
||||
.endpoint(minioUrl)
|
||||
.credentials(minioName, minioPass)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return minioClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到minio
|
||||
* @param stream
|
||||
* @param relativePath
|
||||
* @return
|
||||
*/
|
||||
public static String upload(InputStream stream,String relativePath) throws Exception {
|
||||
initMinio(minioUrl, minioName,minioPass);
|
||||
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
|
||||
log.info("Bucket already exists.");
|
||||
} else {
|
||||
// 创建一个名为ota的存储桶
|
||||
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
|
||||
log.info("create a new bucket.");
|
||||
}
|
||||
PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
|
||||
.bucket(bucketName)
|
||||
.contentType("application/octet-stream")
|
||||
.stream(stream,stream.available(),-1).build();
|
||||
minioClient.putObject(objectArgs);
|
||||
stream.close();
|
||||
return minioUrl+bucketName+"/"+relativePath;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+330
-387
@@ -1,387 +1,330 @@
|
||||
package com.jero.modules.system.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.api.vo.Result;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import com.jero.common.system.api.ISysBaseAPI;
|
||||
import com.jero.common.util.CommonUtils;
|
||||
import com.jero.common.util.RestUtil;
|
||||
import com.jero.common.util.TokenUtils;
|
||||
import com.jero.common.util.oConvertUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.URLDecoder;
|
||||
/**
|
||||
* <p>
|
||||
* 用户表 前端控制器
|
||||
* </p>
|
||||
*
|
||||
* @Author scott
|
||||
* @since 2018-12-20
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/sys/common")
|
||||
public class CommonController {
|
||||
|
||||
@Autowired
|
||||
private ISysBaseAPI sysBaseAPI;
|
||||
|
||||
@Value(value = "${jero.path.upload}")
|
||||
private String uploadpath;
|
||||
|
||||
/**
|
||||
* 本地:local minio:minio 阿里:alioss
|
||||
*/
|
||||
@Value(value="${jero.uploadType}")
|
||||
private String uploadType;
|
||||
|
||||
/**
|
||||
* @Author 政辉
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/403")
|
||||
public Result<?> noauth() {
|
||||
return Result.error("没有权限,请联系管理员授权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传统一方法
|
||||
* @param request
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@PostMapping(value = "/upload")
|
||||
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
|
||||
Result<?> result = new Result<>();
|
||||
String savePath = "";
|
||||
String bizPath = request.getParameter("biz");
|
||||
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
|
||||
MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
|
||||
if(oConvertUtils.isEmpty(bizPath)){
|
||||
if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
|
||||
//未指定目录,则用阿里云默认目录 upload
|
||||
bizPath = "upload";
|
||||
//result.setMessage("使用阿里云文件上传时,必须添加目录!");
|
||||
//result.setSuccess(false);
|
||||
//return result;
|
||||
}else{
|
||||
bizPath = "";
|
||||
}
|
||||
}
|
||||
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
|
||||
//update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
|
||||
savePath = this.uploadLocal(file,bizPath);
|
||||
//update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
|
||||
/** 富文本编辑器及markdown本地上传时,采用返回链接方式
|
||||
//针对jeditor编辑器如何使 lcaol模式,采用 base64格式存储
|
||||
String jeditor = request.getParameter("jeditor");
|
||||
if(oConvertUtils.isNotEmpty(jeditor)){
|
||||
result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
|
||||
result.setSuccess(true);
|
||||
return result;
|
||||
}else{
|
||||
savePath = this.uploadLocal(file,bizPath);
|
||||
}
|
||||
*/
|
||||
}else{
|
||||
//update-begin-author:taoyan date:20200814 for:文件上传改造
|
||||
savePath = CommonUtils.upload(file, bizPath, uploadType);
|
||||
//update-end-author:taoyan date:20200814 for:文件上传改造
|
||||
}
|
||||
if(oConvertUtils.isNotEmpty(savePath)){
|
||||
result.setMessage(savePath);
|
||||
result.setSuccess(true);
|
||||
}else {
|
||||
result.setMessage("上传失败!");
|
||||
result.setSuccess(false);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地文件上传
|
||||
* @param mf 文件
|
||||
* @param bizPath 自定义路径
|
||||
* @return
|
||||
*/
|
||||
private String uploadLocal(MultipartFile mf,String bizPath){
|
||||
try {
|
||||
String ctxPath = uploadpath;
|
||||
String fileName = null;
|
||||
File file = new File(ctxPath + File.separator + bizPath + File.separator );
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();// 创建文件根目录
|
||||
}
|
||||
String orgName = mf.getOriginalFilename();// 获取文件名
|
||||
orgName = CommonUtils.getFileName(orgName);
|
||||
if(orgName.indexOf(".")!=-1){
|
||||
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
|
||||
}else{
|
||||
fileName = orgName+ "_" + System.currentTimeMillis();
|
||||
}
|
||||
String savePath = file.getPath() + File.separator + fileName;
|
||||
File savefile = new File(savePath);
|
||||
FileCopyUtils.copy(mf.getBytes(), savefile);
|
||||
String dbpath = null;
|
||||
if(oConvertUtils.isNotEmpty(bizPath)){
|
||||
dbpath = bizPath + File.separator + fileName;
|
||||
}else{
|
||||
dbpath = fileName;
|
||||
}
|
||||
if (dbpath.contains("\\")) {
|
||||
dbpath = dbpath.replace("\\", "/");
|
||||
}
|
||||
return dbpath;
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// @PostMapping(value = "/upload2")
|
||||
// public Result<?> upload2(HttpServletRequest request, HttpServletResponse response) {
|
||||
// Result<?> result = new Result<>();
|
||||
// try {
|
||||
// String ctxPath = uploadpath;
|
||||
// String fileName = null;
|
||||
// String bizPath = "files";
|
||||
// String tempBizPath = request.getParameter("biz");
|
||||
// if(oConvertUtils.isNotEmpty(tempBizPath)){
|
||||
// bizPath = tempBizPath;
|
||||
// }
|
||||
// String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
|
||||
// File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
|
||||
// if (!file.exists()) {
|
||||
// file.mkdirs();// 创建文件根目录
|
||||
// }
|
||||
// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
|
||||
// MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
|
||||
// String orgName = mf.getOriginalFilename();// 获取文件名
|
||||
// fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
|
||||
// String savePath = file.getPath() + File.separator + fileName;
|
||||
// File savefile = new File(savePath);
|
||||
// FileCopyUtils.copy(mf.getBytes(), savefile);
|
||||
// String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
|
||||
// if (dbpath.contains("\\")) {
|
||||
// dbpath = dbpath.replace("\\", "/");
|
||||
// }
|
||||
// result.setMessage(dbpath);
|
||||
// result.setSuccess(true);
|
||||
// } catch (IOException e) {
|
||||
// result.setSuccess(false);
|
||||
// result.setMessage(e.getMessage());
|
||||
// log.error(e.getMessage(), e);
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 预览图片&下载文件
|
||||
* 请求地址:http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
*/
|
||||
@GetMapping(value = "/static/**")
|
||||
public void view(HttpServletRequest request, HttpServletResponse response) {
|
||||
// ISO-8859-1 ==> UTF-8 进行编码转换
|
||||
String imgPath = extractPathFromPattern(request);
|
||||
if(oConvertUtils.isEmpty(imgPath) || imgPath=="null"){
|
||||
return;
|
||||
}
|
||||
// 其余处理略
|
||||
InputStream inputStream = null;
|
||||
OutputStream outputStream = null;
|
||||
try {
|
||||
imgPath = imgPath.replace("..", "");
|
||||
if (imgPath.endsWith(",")) {
|
||||
imgPath = imgPath.substring(0, imgPath.length() - 1);
|
||||
}
|
||||
String filePath = uploadpath + File.separator + imgPath;
|
||||
File file = new File(filePath);
|
||||
if(!file.exists()){
|
||||
response.setStatus(404);
|
||||
throw new RuntimeException("文件不存在..");
|
||||
}
|
||||
response.setContentType("application/force-download");// 设置强制下载不打开
|
||||
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
|
||||
inputStream = new BufferedInputStream(new FileInputStream(filePath));
|
||||
outputStream = response.getOutputStream();
|
||||
byte[] buf = new byte[1024];
|
||||
int len;
|
||||
while ((len = inputStream.read(buf)) > 0) {
|
||||
outputStream.write(buf, 0, len);
|
||||
}
|
||||
response.flushBuffer();
|
||||
} catch (IOException e) {
|
||||
log.error("预览文件失败" + e.getMessage());
|
||||
response.setStatus(404);
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
if (outputStream != null) {
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 下载文件
|
||||
// * 请求地址:http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
|
||||
// *
|
||||
// * @param request
|
||||
// * @param response
|
||||
// * @throws Exception
|
||||
// */
|
||||
// @GetMapping(value = "/download/**")
|
||||
// public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// // ISO-8859-1 ==> UTF-8 进行编码转换
|
||||
// String filePath = extractPathFromPattern(request);
|
||||
// // 其余处理略
|
||||
// InputStream inputStream = null;
|
||||
// OutputStream outputStream = null;
|
||||
// try {
|
||||
// filePath = filePath.replace("..", "");
|
||||
// if (filePath.endsWith(",")) {
|
||||
// filePath = filePath.substring(0, filePath.length() - 1);
|
||||
// }
|
||||
// String localPath = uploadpath;
|
||||
// String downloadFilePath = localPath + File.separator + filePath;
|
||||
// File file = new File(downloadFilePath);
|
||||
// if (file.exists()) {
|
||||
// response.setContentType("application/force-download");// 设置强制下载不打开
|
||||
// response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
|
||||
// inputStream = new BufferedInputStream(new FileInputStream(file));
|
||||
// outputStream = response.getOutputStream();
|
||||
// byte[] buf = new byte[1024];
|
||||
// int len;
|
||||
// while ((len = inputStream.read(buf)) > 0) {
|
||||
// outputStream.write(buf, 0, len);
|
||||
// }
|
||||
// response.flushBuffer();
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// log.info("文件下载失败" + e.getMessage());
|
||||
// // e.printStackTrace();
|
||||
// } finally {
|
||||
// if (inputStream != null) {
|
||||
// try {
|
||||
// inputStream.close();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// if (outputStream != null) {
|
||||
// try {
|
||||
// outputStream.close();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
/**
|
||||
* @功能:pdf预览Iframe
|
||||
* @param modelAndView
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/pdf/pdfPreviewIframe")
|
||||
public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
|
||||
modelAndView.setViewName("pdfPreviewIframe");
|
||||
return modelAndView;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把指定URL后的字符串全部截断当成参数
|
||||
* 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private static String extractPathFromPattern(final HttpServletRequest request) {
|
||||
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
|
||||
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 中转HTTP请求,解决跨域问题
|
||||
*
|
||||
* @param url 必填:请求地址
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/transitRESTful")
|
||||
public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
|
||||
try {
|
||||
ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
|
||||
// 中转请求method、body
|
||||
HttpMethod method = httpRequest.getMethod();
|
||||
JSONObject params;
|
||||
try {
|
||||
params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
|
||||
} catch (Exception e) {
|
||||
params = new JSONObject();
|
||||
}
|
||||
// 中转请求问号参数
|
||||
JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
|
||||
variables.remove("url");
|
||||
// 在 headers 里传递Token
|
||||
String token = TokenUtils.getTokenByRequest(request);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("X-Access-Token", token);
|
||||
// 发送请求
|
||||
String httpURL = URLDecoder.decode(url, "UTF-8");
|
||||
ResponseEntity<String> response = RestUtil.request(httpURL, method, headers , variables, params, String.class);
|
||||
// 封装返回结果
|
||||
Result<Object> result = new Result<>();
|
||||
int statusCode = response.getStatusCodeValue();
|
||||
result.setCode(statusCode);
|
||||
result.setSuccess(statusCode == 200);
|
||||
String responseBody = response.getBody();
|
||||
try {
|
||||
// 尝试将返回结果转为JSON
|
||||
Object json = JSON.parse(responseBody);
|
||||
result.setResult(json);
|
||||
} catch (Exception e) {
|
||||
// 转成JSON失败,直接返回原始数据
|
||||
result.setResult(responseBody);
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.debug("中转HTTP请求失败", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
package com.jero.modules.system.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.jero.common.util.*;
|
||||
import com.jero.modules.oss.entity.OSSFile;
|
||||
import com.jero.modules.oss.service.IOSSFileService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.api.vo.Result;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import com.jero.common.system.api.ISysBaseAPI;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.URLDecoder;
|
||||
/**
|
||||
* <p>
|
||||
* 用户表 前端控制器
|
||||
* </p>
|
||||
*
|
||||
* @Author scott
|
||||
* @since 2018-12-20
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/sys/common")
|
||||
public class CommonController {
|
||||
|
||||
@Autowired
|
||||
private ISysBaseAPI sysBaseAPI;
|
||||
|
||||
@Resource
|
||||
private IOSSFileService ossFileService;
|
||||
|
||||
@Value(value = "${jero.path.upload}")
|
||||
private String uploadpath;
|
||||
|
||||
/**
|
||||
* 本地:local minio:minio 阿里:alioss
|
||||
*/
|
||||
@Value(value="${jero.uploadType}")
|
||||
private String uploadType;
|
||||
|
||||
/**
|
||||
* @Author 政辉
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/403")
|
||||
public Result<?> noauth() {
|
||||
return Result.error("没有权限,请联系管理员授权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传统一方法
|
||||
* @param request
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@PostMapping(value = "/upload")
|
||||
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
|
||||
Result<?> result = new Result<>();
|
||||
String savePath = "";
|
||||
String bizPath = request.getParameter("biz");
|
||||
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
|
||||
// 获取上传文件对象
|
||||
MultipartFile file = multipartRequest.getFile("file");
|
||||
if(oConvertUtils.isEmpty(bizPath)){
|
||||
bizPath = "";
|
||||
}
|
||||
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
|
||||
// 本地上传
|
||||
savePath = CommonUtils.uploadLocal(file,bizPath,uploadpath);
|
||||
}else{
|
||||
// minio上传
|
||||
savePath = CommonUtils.upload(file, bizPath, uploadType);
|
||||
}
|
||||
if(oConvertUtils.isNotEmpty(savePath)){
|
||||
result.setMessage(savePath);
|
||||
result.setSuccess(true);
|
||||
//上传成功 进行数据库存储
|
||||
OSSFile ossFile = new OSSFile();
|
||||
String fileName = file.getOriginalFilename();
|
||||
fileName = CommonUtils.getFileName(fileName);
|
||||
ossFile.setFileName(fileName);
|
||||
ossFile.setUrl(savePath);
|
||||
ossFileService.save(ossFile);
|
||||
}else {
|
||||
result.setMessage("上传失败!");
|
||||
result.setSuccess(false);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览图片&下载文件
|
||||
* 请求地址:http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
*/
|
||||
@GetMapping(value = "/download/**")
|
||||
public void view(HttpServletRequest request, HttpServletResponse response) {
|
||||
// ISO-8859-1 ==> UTF-8 进行编码转换
|
||||
String imgPath = extractPathFromPattern(request);
|
||||
if(oConvertUtils.isEmpty(imgPath) || imgPath == "null"){
|
||||
return;
|
||||
}
|
||||
// 其余处理略
|
||||
InputStream inputStream = null;
|
||||
OutputStream outputStream = null;
|
||||
try {
|
||||
imgPath = imgPath.replace("..", "");
|
||||
if (imgPath.endsWith(",")) {
|
||||
imgPath = imgPath.substring(0, imgPath.length() - 1);
|
||||
}
|
||||
String fileName = "";
|
||||
LambdaQueryWrapper<OSSFile> queryWrapper = new LambdaQueryWrapper<>();
|
||||
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
|
||||
//本地下载
|
||||
String filePath = uploadpath + File.separator + imgPath;
|
||||
File file = new File(filePath);
|
||||
if(!file.exists()){
|
||||
response.setStatus(404);
|
||||
throw new RuntimeException("文件不存在..");
|
||||
}
|
||||
// 查询数据表数据是否存在
|
||||
queryWrapper.eq(OSSFile::getUrl,imgPath);
|
||||
OSSFile ossFile = ossFileService.getOne(queryWrapper);
|
||||
if( null == ossFile){
|
||||
throw new RuntimeException("文件不存在..");
|
||||
}
|
||||
// 文件名称
|
||||
fileName = file.getName();
|
||||
inputStream = new BufferedInputStream(new FileInputStream(filePath));
|
||||
}else if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
|
||||
// minio 下载
|
||||
queryWrapper.eq(OSSFile::getUrl,imgPath.replaceFirst("/","//"));
|
||||
OSSFile ossFile = ossFileService.getOne(queryWrapper);
|
||||
// 查询该文件数据是否存在
|
||||
if( null == ossFile){
|
||||
throw new RuntimeException("文件不存在");
|
||||
}
|
||||
// 通过MinioUtil查询时 只需要 桶后面的路径
|
||||
String minioUrl = MinioUtil.getMinioUrl();
|
||||
// Linux/unix 系统下文件路径分隔符为"/" 获取minio与存储桶的路径
|
||||
minioUrl = minioUrl + MinioUtil.getBucketName() + "/";
|
||||
String url = ossFile.getUrl().replace(minioUrl, "");
|
||||
// 文件名称
|
||||
fileName = ossFile.getFileName();
|
||||
inputStream = MinioUtil.getMinioFile(MinioUtil.getBucketName(), url);
|
||||
}
|
||||
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
|
||||
response.setContentType("application/force-download");// 设置强制下载不打开
|
||||
outputStream = response.getOutputStream();
|
||||
byte[] buf = new byte[1024];
|
||||
int len;
|
||||
while ((len = inputStream.read(buf)) > 0) {
|
||||
outputStream.write(buf, 0, len);
|
||||
}
|
||||
response.flushBuffer();
|
||||
} catch (IOException e) {
|
||||
log.error("预览文件失败" + e.getMessage());
|
||||
response.setStatus(404);
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
if (outputStream != null) {
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 下载文件
|
||||
// * 请求地址:http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
|
||||
// *
|
||||
// * @param request
|
||||
// * @param response
|
||||
// * @throws Exception
|
||||
// */
|
||||
// @GetMapping(value = "/download/**")
|
||||
// public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// // ISO-8859-1 ==> UTF-8 进行编码转换
|
||||
// String filePath = extractPathFromPattern(request);
|
||||
// // 其余处理略
|
||||
// InputStream inputStream = null;
|
||||
// OutputStream outputStream = null;
|
||||
// try {
|
||||
// filePath = filePath.replace("..", "");
|
||||
// if (filePath.endsWith(",")) {
|
||||
// filePath = filePath.substring(0, filePath.length() - 1);
|
||||
// }
|
||||
// String localPath = uploadpath;
|
||||
// String downloadFilePath = localPath + File.separator + filePath;
|
||||
// File file = new File(downloadFilePath);
|
||||
// if (file.exists()) {
|
||||
// response.setContentType("application/force-download");// 设置强制下载不打开
|
||||
// response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
|
||||
// inputStream = new BufferedInputStream(new FileInputStream(file));
|
||||
// outputStream = response.getOutputStream();
|
||||
// byte[] buf = new byte[1024];
|
||||
// int len;
|
||||
// while ((len = inputStream.read(buf)) > 0) {
|
||||
// outputStream.write(buf, 0, len);
|
||||
// }
|
||||
// response.flushBuffer();
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// log.info("文件下载失败" + e.getMessage());
|
||||
// // e.printStackTrace();
|
||||
// } finally {
|
||||
// if (inputStream != null) {
|
||||
// try {
|
||||
// inputStream.close();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// if (outputStream != null) {
|
||||
// try {
|
||||
// outputStream.close();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
/**
|
||||
* @功能:pdf预览Iframe
|
||||
* @param modelAndView
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/pdf/pdfPreviewIframe")
|
||||
public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
|
||||
modelAndView.setViewName("pdfPreviewIframe");
|
||||
return modelAndView;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把指定URL后的字符串全部截断当成参数
|
||||
* 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private static String extractPathFromPattern(final HttpServletRequest request) {
|
||||
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
|
||||
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 中转HTTP请求,解决跨域问题
|
||||
*
|
||||
* @param url 必填:请求地址
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/transitRESTful")
|
||||
public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
|
||||
try {
|
||||
ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
|
||||
// 中转请求method、body
|
||||
HttpMethod method = httpRequest.getMethod();
|
||||
JSONObject params;
|
||||
try {
|
||||
params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
|
||||
} catch (Exception e) {
|
||||
params = new JSONObject();
|
||||
}
|
||||
// 中转请求问号参数
|
||||
JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
|
||||
variables.remove("url");
|
||||
// 在 headers 里传递Token
|
||||
String token = TokenUtils.getTokenByRequest(request);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("X-Access-Token", token);
|
||||
// 发送请求
|
||||
String httpURL = URLDecoder.decode(url, "UTF-8");
|
||||
ResponseEntity<String> response = RestUtil.request(httpURL, method, headers , variables, params, String.class);
|
||||
// 封装返回结果
|
||||
Result<Object> result = new Result<>();
|
||||
int statusCode = response.getStatusCodeValue();
|
||||
result.setCode(statusCode);
|
||||
result.setSuccess(statusCode == 200);
|
||||
String responseBody = response.getBody();
|
||||
try {
|
||||
// 尝试将返回结果转为JSON
|
||||
Object json = JSON.parse(responseBody);
|
||||
result.setResult(json);
|
||||
} catch (Exception e) {
|
||||
// 转成JSON失败,直接返回原始数据
|
||||
result.setResult(responseBody);
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.debug("中转HTTP请求失败", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user