【修改】CommonController修改上传与下载文件接口

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