初始代码

This commit is contained in:
wangmingwei
2026-04-21 16:49:46 +08:00
parent aae9dc4036
commit f0453ff3a3
2396 changed files with 256575 additions and 0 deletions

20
yunzhupaas-file/pom.xml Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yunzhupaas-java-boot</artifactId>
<groupId>com.yunzhupaas</groupId>
<version>5.2.0-RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yunzhupaas-file</artifactId>
<packaging>pom</packaging>
<modules>
<module>yunzhupaas-file-entity</module>
<module>yunzhupaas-file-biz</module>
<module>yunzhupaas-file-controller</module>
</modules>
</project>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yunzhupaas-file</artifactId>
<groupId>com.yunzhupaas</groupId>
<version>5.2.0-RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yunzhupaas-file-biz</artifactId>
<dependencies>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-file-entity</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-system-biz</artifactId>
<version>${project.version}</version>
</dependency>
<!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-exception</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,18 @@
package com.yunzhupaas.mapper;
import com.yunzhupaas.base.mapper.SuperMapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yunzhupaas.entity.FileEntity;
/**
*
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/13
*/
public interface FileMapper extends SuperMapper<FileEntity> {
}

View File

@@ -0,0 +1,86 @@
package com.yunzhupaas.service;
import com.yunzhupaas.base.service.SuperService;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yunzhupaas.entity.FileEntity;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.model.YozoFileParams;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/13
*/
@Service
public interface YozoService extends SuperService<FileEntity> {
/**
* 生成文件预览url
* @param params
* @return
*/
String getPreviewUrl(YozoFileParams params);
/**
* 新建文档保存versionId
* @param fileVersionId
* @param fileId
* @param fileName
* @return
*/
ActionResult saveFileId(String fileVersionId, String fileId, String fileName);
/**
* 根据文件名查询
* @param fileNa
* @return
*/
FileEntity selectByName(String fileNa);
/**
* 上传文件到永中
* @param fileVersionId
* @param fileId
* @param fileUrl
* @return
*/
ActionResult saveFileIdByHttp(String fileVersionId, String fileId, String fileUrl);
/**
* 删除文件
* @param versionId
* @return
*/
ActionResult deleteFileByVersionId(String versionId);
/**
* 根据versionId查询文件
* @param fileVersionId
* @return
*/
FileEntity selectByVersionId(String fileVersionId);
/**
* 批量删除
* @param versions
* @return
*/
ActionResult deleteBatch(String[] versions);
/**
* 更新versionId
* @param oldFileId
* @param newFileId
*/
void editFileVersion(String oldFileId, String newFileId);
List<FileEntity> getAllList(PaginationVO pageModel);
}

View File

@@ -0,0 +1,149 @@
package com.yunzhupaas.service.impl;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.entity.FileEntity;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.mapper.FileMapper;
import com.yunzhupaas.model.YozoFileParams;
import com.yunzhupaas.service.YozoService;
import com.yunzhupaas.utils.SplicingUrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
/**
*
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/13
*/
@Service
public class YozoServiceImpl extends SuperServiceImpl<FileMapper,FileEntity> implements YozoService {
@Autowired
private FileMapper fileMapper;
@Override
public String getPreviewUrl(YozoFileParams params) {
String previewUrl = SplicingUrlUtil.getPreviewUrl(params);
return previewUrl;
}
@Override
public ActionResult saveFileId(String fileVersionId, String fileId, String fileName) {
FileEntity fileEntity =new FileEntity();
fileEntity.setId(fileId);
fileEntity.setFileName(fileName);
fileEntity.setFileVersionId(fileVersionId);
fileEntity.setType("create");
this.save(fileEntity);
return ActionResult.success(MsgCode.SU001.get());
}
@Override
public FileEntity selectByName(String fileNa) {
QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(FileEntity::getFileName,fileNa);
return this.getOne(wrapper);
}
@Override
public ActionResult saveFileIdByHttp(String fileVersionId, String fileId, String fileUrl) {
String fileName = "";
String url = "";
String name = "";
try {
url = URLDecoder.decode(fileUrl, "UTF-8");
if (url.contains("/")) {
fileName = url.substring(url.lastIndexOf("/") + 1);
} else {
fileName = url.substring(url.lastIndexOf("\\") + 1);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//同一url文件数
QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
wrapper.eq("F_Url", url);
Long total = fileMapper.selectCount(wrapper);
if (total == 0) {
name = fileName;
} else {
String t = total.toString();
name = fileName + "(" + t + ")";
}
FileEntity fileEntity = new FileEntity();
fileEntity.setType(url.contains("http") ? "http" : "local");
fileEntity.setFileVersionId(fileVersionId);
fileEntity.setId(fileId);
fileEntity.setFileName(name);
fileEntity.setUrl(url);
fileMapper.insert(fileEntity);
return ActionResult.success(MsgCode.SU001.get());
}
@Override
public ActionResult deleteFileByVersionId(String versionId) {
QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
wrapper.eq("F_FileVersion", versionId);
int i = fileMapper.delete(wrapper);
if (i == 1) {
return ActionResult.success(MsgCode.SU003.get());
}
return ActionResult.fail(MsgCode.FA003.get());
}
@Override
public FileEntity selectByVersionId(String fileVersionId) {
QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
wrapper.eq("F_FileVersion", fileVersionId);
FileEntity fileEntity = fileMapper.selectOne(wrapper);
return fileEntity;
}
@Override
public ActionResult deleteBatch(String[] versions) {
for (String version : versions) {
QueryWrapper<FileEntity> wrapper = new QueryWrapper<>();
wrapper.eq("F_FileVersion", version);
int i = fileMapper.delete(wrapper);
if (i == 0) {
return ActionResult.fail(MsgCode.FA045.get(version));
}
}
return ActionResult.success(MsgCode.SU003.get());
}
@Override
public void editFileVersion(String oldFileId, String newFileId) {
UpdateWrapper<FileEntity> wrapper = new UpdateWrapper<>();
wrapper.eq("F_FileVersion", oldFileId);
FileEntity fileEntity = new FileEntity();
fileEntity.setFileVersionId(newFileId);
fileEntity.setOldFileVersionId(oldFileId);
fileMapper.update(fileEntity, wrapper);
}
@Override
public List<FileEntity> getAllList(PaginationVO pageModel) {
Page page = new Page(pageModel.getCurrentPage(), pageModel.getPageSize());
IPage<FileEntity> iPage = fileMapper.selectPage(page, null);
return iPage.getRecords();
}
}

View File

@@ -0,0 +1,211 @@
package com.yunzhupaas.utils;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.yozo.client.AppAuthenticator;
import com.yunzhupaas.yozo.client.UaaAppAuthenticator;
import com.yunzhupaas.yozo.utils.DefaultResult;
import com.yunzhupaas.yozo.utils.IResult;
import com.yunzhupaas.model.YozoParams;
import com.yunzhupaas.util.XSSEscape;
import com.yunzhupaas.yozo.constants.EnumResultCode;
import com.yunzhupaas.yozo.constants.UaaConstant;
import lombok.Cleanup;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* 文件预览编辑工具类
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/13
*/
@Component
public class YozoUtils {
/**
* 生成签名
*
* @param appId
* @param secret
* @param params
* @return
*/
public IResult<String> generateSign(String appId, String secret, Map<String, String[]> params) {
AppAuthenticator authenticator = new UaaAppAuthenticator(UaaConstant.SIGN, null, UaaConstant.APPID);
try {
String[] appIds = params.get(UaaConstant.APPID);
if (appIds == null || appIds.length != 1 || StringUtils.isEmpty(appIds[0])) {
params.put(UaaConstant.APPID, new String[]{appId});
}
String sign = authenticator.generateSign(secret, params);
return DefaultResult.successResult(sign);
} catch (Exception e) {
return DefaultResult.failResult(EnumResultCode.E_GENERATE_SIGN_FAIL.getInfo());
}
}
/**
* 获取文件名
* @param fileName
* @param templateType
* @return
*/
public String getFileName(String fileName, String templateType) {
String suffix;
switch (templateType) {
case "1":
suffix = ".doc";
break;
case "2":
suffix = ".docx";
break;
case "3":
suffix = ".ppt";
break;
case "4":
suffix = ".pptx";
break;
case "5":
suffix = ".xls";
break;
case "6":
suffix = ".xlsx";
break;
default:
suffix = null;
}
if (suffix==null){
return null;
}
String name = fileName + suffix;
return name;
}
/**
* 使用httpclint 发送文件
* @author: qingfeng
* @date: 2019-05-27
* @param file
* 上传的文件
*/
public String uploadFile(String url , File file, String appId, String sign) {
String result="";
//构建HttpClient对象
CloseableHttpResponse response = null;
//构建POST请求
HttpPost httpPost = new HttpPost(url);
try {
@Cleanup CloseableHttpClient client = HttpClients.createDefault();
//构建文件体
String fileName = file.getName();
FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA, fileName);
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", fileBody)
.addTextBody("appId",appId)
.addTextBody("sign",sign)
.build();
httpPost.setEntity(httpEntity);
// 执行http请求
response = client.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 下载文件到指定目录
* @param fileUrl
* @param savePath
* @throws Exception
*/
public void downloadFile(String fileUrl,String savePath) throws Exception {
File file=new File(XSSEscape.escapePath(savePath));
//判断文件是否存在,不存在则创建文件
if(!file.exists()){
file.createNewFile();
}
URL url = new URL(fileUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception(MsgCode.FA046.get());
}
@Cleanup DataInputStream in = new DataInputStream(urlCon.getInputStream());
@Cleanup FileOutputStream fileOutputStream = new FileOutputStream(savePath);
@Cleanup DataOutputStream out = new DataOutputStream(fileOutputStream);
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
try {
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上传文件到永中
* @param
* @return
*/
public String uploadFileInPreview(InputStream inputStream,String fileName) throws IOException {
//获取签名
Map<String, String[]> parameter = new HashMap<String, String[]>();
parameter.put("appId", new String[]{YozoParams.APP_ID});
String sign = this.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, parameter).getData();
String url= "http://dmc.yozocloud.cn/api/file/upload?appId="+YozoParams.APP_ID+"&sign="+sign;
@Cleanup CloseableHttpClient httpClient = HttpClients.createDefault();
String result ="";
HttpEntity httpEntity =null;
HttpEntity responseEntity = null;
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(Charset.forName("utf-8"));
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
multipartEntityBuilder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
responseEntity = response.getEntity();
result = EntityUtils.toString(responseEntity,Charset.forName("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}finally {
if (inputStream!=null){
inputStream.close();
}
}
return result;
}
}

View File

@@ -0,0 +1,8 @@
package com.yunzhupaas.yozo.client;
import java.util.Map;
public interface AppAuthenticator {
String generateSign(String var1, Map<String, String[]> var2) throws Exception;
}

View File

@@ -0,0 +1,99 @@
package com.yunzhupaas.yozo.client;
import com.yunzhupaas.yozo.utils.SecretSignatureUtils;
import com.yunzhupaas.util.StringUtil;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
public class UaaAppAuthenticator implements AppAuthenticator {
public static final String OPEN_PARAM_PREFIX = "y_";
public static final String OPEN_PARAM_APPID = "y_appid";
public static final String OPEN_PARAM_SIGN = "y_SIGN";
private String signParamName;
private String paramNamePrefix;
private String appidParamName;
public UaaAppAuthenticator() {
}
public UaaAppAuthenticator(String signParamName, String paramNamePrefix, String appidParamName) {
this.signParamName = signParamName;
this.paramNamePrefix = paramNamePrefix;
this.appidParamName = appidParamName;
}
public String getSignParamName() {
return this.signParamName;
}
public void setSignParamName(String signParamName) {
this.signParamName = signParamName;
}
public String getParamNamePrefix() {
return this.paramNamePrefix;
}
public void setParamNamePrefix(String paramNamePrefix) {
this.paramNamePrefix = paramNamePrefix;
}
public String getAppidParamName() {
return this.appidParamName;
}
public void setAppidParamName(String appidParamName) {
this.appidParamName = appidParamName;
}
public String generateSign(String secret, Map<String, String[]> params) throws Exception {
String fullParamStr = this.uniqSortParams(params);
return SecretSignatureUtils.hmacSHA256(fullParamStr, secret);
}
private String uniqSortParams(Map<String, String[]> params) {
boolean prefix = StringUtil.isNotEmpty(this.paramNamePrefix);
params.remove(this.signParamName);
String[] paramKeys = new String[params.keySet().size()];
int idx = 0;
Iterator var5 = params.keySet().iterator();
while(true) {
String param;
do {
if (!var5.hasNext()) {
Arrays.sort(paramKeys, 0, idx);
StringBuilder builder = new StringBuilder();
String[] var16 = paramKeys;
int var7 = paramKeys.length;
for(int var8 = 0; var8 < var7; ++var8) {
String key = var16[var8];
String[] values = (String[])((String[])params.get(key));
if (values != null && values.length > 0) {
Arrays.sort(values);
String[] var11 = values;
int var12 = values.length;
for(int var13 = 0; var13 < var12; ++var13) {
String val = var11[var13];
builder.append(key).append("=").append(val);
}
} else {
builder.append(key).append("=");
}
}
return builder.toString();
}
param = (String)var5.next();
} while(prefix && param.startsWith(this.paramNamePrefix));
paramKeys[idx++] = param;
}
}
}

View File

@@ -0,0 +1,29 @@
package com.yunzhupaas.yozo.client;
import com.yunzhupaas.yozo.utils.DefaultResult;
import com.yunzhupaas.yozo.utils.IResult;
import com.yunzhupaas.yozo.constants.EnumResultCode;
import java.util.Map;
public class UaaAppConfigClient {
public UaaAppConfigClient() {
}
public IResult<String> generateSign(String appId, String secret, Map<String, String[]> params) {
UaaAppAuthenticator authenticator = new UaaAppAuthenticator("sign", (String)null, "appId");
try {
String[] appIds = (String[])params.get("appId");
if (appIds == null || appIds.length != 1 || appIds[0] == null || "".equals(appIds[0])) {
params.put("appId", new String[]{appId});
}
String sign = authenticator.generateSign(secret, params);
return DefaultResult.successResult(sign);
} catch (Exception var7) {
return DefaultResult.failResult(EnumResultCode.E_GENERATE_SIGN_FAIL.getInfo());
}
}
}

View File

@@ -0,0 +1,37 @@
package com.yunzhupaas.yozo.constants;
public enum EnumResultCode {
E_SUCCESS(0, "操作成功"),
E_GENERATE_SIGN_FAIL(1000, "获取签名失败");
private Integer value;
private String info;
private EnumResultCode(Integer value, String info) {
this.value = value;
this.info = info;
}
public Integer getValue() {
return this.value;
}
public String getInfo() {
return this.info;
}
public static EnumResultCode getEnum(Integer value) {
EnumResultCode[] var1 = values();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
EnumResultCode code = var1[var3];
if (code.getValue().equals(value)) {
return code;
}
}
return null;
}
}

View File

@@ -0,0 +1,10 @@
package com.yunzhupaas.yozo.constants;
public class UaaConstant {
public static final String APPID = "appId";
public static final String SIGN = "sign";
public UaaConstant() {
}
}

View File

@@ -0,0 +1,87 @@
package com.yunzhupaas.yozo.utils;
public class DefaultResult<T> implements IResult<T> {
private static final DefaultResult.SuccessResult SUCCESS = new DefaultResult.SuccessResult();
private static final DefaultResult.FailResult FAIL = new DefaultResult.FailResult();
private boolean success;
private String message;
private T data;
public DefaultResult() {
}
public DefaultResult(boolean success, String message) {
this(success, message, (T) null);
}
public DefaultResult(boolean success, T data) {
this(success, (String)null, data);
}
public DefaultResult(boolean success, String message, T data) {
this.success = success;
this.message = message;
this.data = data;
}
public static <T> DefaultResult<T> successResult() {
return (DefaultResult<T>) SUCCESS;
}
public static <T> DefaultResult<T> successResult(T data) {
return new DefaultResult(true, (String)null, data);
}
public static <T> DefaultResult<T> successResult(String message, T data) {
return new DefaultResult(true, message, data);
}
public static <T> DefaultResult<T> failResult() {
return (DefaultResult<T>) FAIL;
}
public static <T> DefaultResult<T> failResult(String message) {
return new DefaultResult(false, message, (Object)null);
}
public static <T> DefaultResult<T> failResult(String message, T data) {
return new DefaultResult(false, message, data);
}
public static <T> DefaultResult<T> failResult(T data) {
return new DefaultResult(false, (String)null, data);
}
public static <T> DefaultResult<T> result(boolean success, String message, T data) {
return new DefaultResult(success, message, data);
}
public boolean isSuccess() {
return this.success;
}
public String getMessage() {
return this.message;
}
public T getData() {
return this.data;
}
public void setData(T obj) {
this.data = obj;
}
private static class FailResult extends DefaultResult<Object> {
public FailResult() {
super(false, (String)null, (Object)null);
}
}
private static class SuccessResult extends DefaultResult<Object> {
public SuccessResult() {
super(true, (String)null, (Object)null);
}
}
}

View File

@@ -0,0 +1,26 @@
package com.yunzhupaas.yozo.utils;
public class HttpRequestUtils {
public HttpRequestUtils() {
}
public static class StringUtils {
public StringUtils() {
}
public static boolean isNotEmpty(String data) {
return data != null && data.trim().length() > 0;
}
public static boolean equals(String cs1, String cs2) {
if (cs1 == cs2) {
return true;
} else if (cs1 != null && cs2 != null) {
return cs1.length() != cs2.length() ? false : cs1.equals(cs2);
} else {
return false;
}
}
}
}

View File

@@ -0,0 +1,12 @@
package com.yunzhupaas.yozo.utils;
public interface IResult<T> {
boolean isSuccess();
String getMessage();
T getData();
void setData(T var1);
}

View File

@@ -0,0 +1,29 @@
package com.yunzhupaas.yozo.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SecretSignatureUtils {
public static final String SHA256 = "HmacSHA256";
public SecretSignatureUtils() {
}
public static String hmacSHA256(String data, String key) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
mac.init(secret_key);
byte[] array = mac.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
byte[] var6 = array;
int var7 = array.length;
for(int var8 = 0; var8 < var7; ++var8) {
byte item = var6[var8];
sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
}
return sb.toString().toUpperCase();
}
}

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yunzhupaas-file</artifactId>
<groupId>com.yunzhupaas</groupId>
<version>5.2.0-RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yunzhupaas-file-controller</artifactId>
<dependencies>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-file-biz</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,846 @@
package com.yunzhupaas.controller;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.DictionaryDataEntity;
import com.yunzhupaas.base.service.DictionaryDataService;
import com.yunzhupaas.base.util.OptimizeUtil;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.base.vo.ListVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.FileTypeConstant;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.consts.DeviceType;
import com.yunzhupaas.entity.FileDetail;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.model.*;
import com.yunzhupaas.util.*;
import com.yunzhupaas.utils.YozoUtils;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* 通用控制器
*
* @author 云筑产品开发平台组
* @version v5.2.7
* @copyright 深圳市乐程软件有限公司
* @date 2024-09-26 上午9:18
*/
@Slf4j
@Tag(name = "公共", description = "file")
@RestController
@RequestMapping("/api/file")
public class UtilsController {
@Autowired
private ConfigValueUtil configValueUtil;
@Autowired
private RedisUtil redisUtil;
@Autowired
private DictionaryDataService dictionaryDataService;
@Autowired
private YozoUtils yozoUtils;
/**
* 语言列表
*
* @return
*/
@Operation(summary = "语言列表")
@GetMapping("/Language")
public ActionResult<ListVO<LanguageVO>> getList() {
String dictionaryTypeId = "dc6b2542d94b407cac61ec1d59592901";
List<DictionaryDataEntity> list = dictionaryDataService.getList(dictionaryTypeId);
List<LanguageVO> language = JsonUtil.getJsonToList(list, LanguageVO.class);
ListVO vo = new ListVO();
vo.setList(language);
return ActionResult.success(vo);
}
/**
* 图形验证码
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "图形验证码")
@GetMapping("/ImageCode/{timestamp}")
@Parameters({
@Parameter(name = "timestamp", description = "时间戳", required = true),
})
public void imageCode(@PathVariable("timestamp") String timestamp) {
DownUtil.downCode(null);
redisUtil.insert(timestamp, ServletUtil.getSession().getAttribute(CodeUtil.RANDOMCODEKEY), 120);
}
/**
* 获取全部下载文件链接(打包下载)
*
* @return
*/
@NoDataSourceBind
@Operation(summary = "获取全部下载文件链接(打包下载)")
@PostMapping("/PackDownload/{type}")
public ActionResult packDownloadUrl(@PathVariable("type") String type,
@RequestBody List<Map<String, String>> fileInfoList) throws Exception {
type = XSSEscape.escape(type);
if (fileInfoList == null || fileInfoList.isEmpty()) {
return ActionResult.fail(MsgCode.FA047.get());
}
List<String> filePathList = new ArrayList<String>();
String zipTempFilePath = null;
String zipFileId = RandomUtil.uuId() + ".zip";
List<String> repeatName = new ArrayList<>();
for (Map fileInfoMap : fileInfoList) {
String fileId = XSSEscape.escape((String) fileInfoMap.get("fileId")).trim();
String fileName = XSSEscape.escape((String) fileInfoMap.get("fileName")).trim();
if (repeatName.contains(fileName)) {
fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "副本"
+ UUID.randomUUID().toString().substring(0, 5) + fileName.substring(fileName.lastIndexOf("."));
} else {
repeatName.add(fileName);
}
if (StringUtil.isEmpty(fileId) || StringUtil.isEmpty(fileName)) {
continue;
}
if (FileUploadUtils.exists(type, fileId)) {
String typePath = FilePathUtil.getFilePath(type);
if (fileId.indexOf(",") >= 0) {
typePath += fileId.substring(0, fileId.lastIndexOf(",") + 1).replaceAll(",", "/");
fileId = fileId.substring(fileId.lastIndexOf(",") + 1);
}
byte[] bytes = FileUploadUtils.downloadFileByte(typePath, fileId, false);
if (zipTempFilePath == null) {
zipTempFilePath = FileUploadUtils.getLocalBasePath()
+ FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH);
if (!new File(zipTempFilePath).exists()) {
new File(zipTempFilePath).mkdirs();
}
zipTempFilePath += zipFileId;
}
ZipUtil.fileAddToZip(zipTempFilePath, new ByteArrayInputStream(bytes), fileName);
}
}
if (zipTempFilePath == null) {
return ActionResult.fail(MsgCode.FA018.get());
}
// 将文件上传到默认文件服务器
String newFileId = zipFileId;
if (!"local".equals(FileUploadUtils.getDefaultPlatform())) { // 不是本地说明是其他文件服务器将zip文件上传到其他服务器里方便下载
FileInfo fileInfo = FileUploadUtils.uploadFile(new File(zipTempFilePath),
FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH), zipFileId);
new File(zipTempFilePath).delete();
newFileId = fileInfo.getFilename();
}
com.yunzhupaas.base.vo.DownloadVO vo = DownloadVO.builder().name(zipFileId)
.url(UploaderUtil.uploaderFile(newFileId + "#" + FileTypeConstant.FILEZIPDOWNTEMPPATH)).build();
Map<String, Object> map = new HashMap<String, Object>();
map.put("downloadVo", vo);
map.put("downloadName", "文件" + zipFileId);
return ActionResult.success(map);
}
/**
* 上传文件/图片
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "上传文件/图片")
@PostMapping(value = "/Uploader/{type}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Parameters({
@Parameter(name = "type", description = "类型", required = true)
})
public ActionResult<UploaderVO> uploader(@PathVariable("type") String type, MultipartFile file,
HttpServletRequest httpServletRequest) throws IOException {
String fileType = UpUtil.getFileType(file);
// 验证类型
if (!OptimizeUtil.fileType(configValueUtil.getAllowUploadFileType(), fileType)) {
return ActionResult.fail(MsgCode.FA017.get());
}
PathTypeModel pathTypeModel = new PathTypeModel();
pathTypeModel.setPathType(httpServletRequest.getParameter("pathType"));
pathTypeModel.setTimeFormat(httpServletRequest.getParameter("timeFormat"));
pathTypeModel.setSortRule(httpServletRequest.getParameter("sortRule"));
pathTypeModel.setFolder(httpServletRequest.getParameter("folder"));
if ("selfPath".equals(pathTypeModel.getPathType())) {
if (StringUtil.isNotEmpty(pathTypeModel.getFolder())) {
String folder = pathTypeModel.getFolder();
folder = folder.replaceAll("\\\\", "/");
// String regex = "^[a-z0-9A-Z\\u4e00-\\u9fa5\\\\\\/]+$";
String regex = "^[a-zA-Z0-9][a-zA-Z0-9_\\-\\\\\\/]{0,99}$";
if (!folder.matches(regex)) {
return ActionResult.fail(MsgCode.FA038.get());
}
}
}
UploaderVO vo = uploaderVO(file, type, pathTypeModel);
return ActionResult.success(vo);
}
/**
* 图片转成base64
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "图片转成base64")
@PostMapping(value = "/Uploader/imgToBase64", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ActionResult imgToBase64(@RequestParam("file") MultipartFile file) throws IOException {
String encode = cn.hutool.core.codec.Base64.encode(file.getBytes());
Object base64Name = "";
if (StringUtil.isNotEmpty(encode)) {
base64Name = "data:image/jpeg;base64," + encode;
}
return ActionResult.success(base64Name);
}
/**
* 获取下载文件链接
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "获取下载文件链接")
@GetMapping("/Download/{type}/{fileName}")
@Parameters({
@Parameter(name = "type", description = "类型", required = true),
@Parameter(name = "fileName", description = "文件名称", required = true),
})
public ActionResult downloadUrl(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
type = XSSEscape.escape(type);
fileName = XSSEscape.escape(fileName);
boolean exists = FileUploadUtils.exists(type, fileName);
if (exists) {
DownloadVO vo = DownloadVO.builder().name(fileName).url(UploaderUtil.uploaderFile(fileName + "#" + type))
.build();
return ActionResult.success(vo);
}
return ActionResult.fail(MsgCode.FA018.get());
}
/**
* 下载文件链接
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "下载文件链接")
@GetMapping("/Download")
public void downloadFile() throws DataException {
HttpServletRequest request = ServletUtil.getRequest();
String reqJson = request.getParameter("encryption");
String name = request.getParameter("name");
String fileNameAll = DesUtil.aesDecode(reqJson);
if (!StringUtil.isEmpty(fileNameAll)) {
fileNameAll = fileNameAll.replaceAll("\n", "");
String[] data = fileNameAll.split("#");
String cacheKEY = data.length > 0 ? data[0] : "";
String fileName = XSSEscape.escapePath(data.length > 1 ? data[1] : "");
String type = data.length > 2 ? data[2] : "";
Object ticketObj = TicketUtil.parseTicket(cacheKEY);
// 验证缓存
if (ticketObj != null) {
// 某些手机浏览器下载后会有提示窗口, 会访问两次下载地址
if (UserProvider.getDeviceForAgent().equals(DeviceType.APP) && "".equals(ticketObj)) {
TicketUtil.updateTicket(cacheKEY, "1", 30L);
} else {
TicketUtil.deleteTicket(cacheKEY);
}
// 下载文件
String typePath = FilePathUtil.getFilePath(type.toLowerCase());
if (fileName.indexOf(",") >= 0) {
typePath += fileName.substring(0, fileName.lastIndexOf(",") + 1).replaceAll(",", "/");
fileName = fileName.substring(fileName.lastIndexOf(",") + 1);
}
// String filePath = FilePathUtil.getFilePath(type.toLowerCase());
byte[] bytes = FileUploadUtils.downloadFileByte(typePath, fileName, false);
FileDownloadUtil.downloadFile(bytes, fileName, name);
if (FileTypeConstant.FILEZIPDOWNTEMPPATH.equals(type)) { // 删除打包的临时文件,释放存储
FileUploadUtils.deleteFileByPathAndFileName(typePath, fileName);
}
} else {
if (FileTypeConstant.FILEZIPDOWNTEMPPATH.equals(type)) { // 删除打包的临时文件,释放存储
String typePath = FilePathUtil.getFilePath(type);
FileUploadUtils.deleteFileByPathAndFileName(typePath, fileName);
}
throw new DataException(MsgCode.FA039.get());
}
} else {
throw new DataException(MsgCode.FA039.get());
}
}
/**
* 下载文件链接
*
* @return
*/
@NoDataSourceBind()
@Operation(summary = "下载模板文件链接")
@GetMapping("/DownloadModel")
public void downloadModel() throws DataException {
HttpServletRequest request = ServletUtil.getRequest();
String reqJson = request.getParameter("encryption");
String fileNameAll = DesUtil.aesDecode(reqJson);
if (!StringUtil.isEmpty(fileNameAll)) {
String token = fileNameAll.split("#")[0];
if (TicketUtil.parseTicket(token) != null) {
TicketUtil.deleteTicket(token);
String fileName = fileNameAll.split("#")[1];
String filePath = configValueUtil.getTemplateFilePath();
// 下载文件
byte[] bytes = FileUploadUtils.downloadFileByte(filePath, fileName, false);
FileDownloadUtil.downloadFile(bytes, fileName, null);
} else {
throw new DataException(MsgCode.FA039.get());
}
} else {
throw new DataException(MsgCode.FA039.get());
}
}
/**
* 获取图片
*
* @param fileName
* @param type
* @return
*/
@NoDataSourceBind()
@Operation(summary = "获取图片")
@GetMapping("/Image/{type}/{fileName}")
@Parameters({
@Parameter(name = "type", description = "类型", required = true),
@Parameter(name = "fileName", description = "名称", required = true),
})
public void downLoadImg(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
String filePath = FilePathUtil.getFilePath(type.toLowerCase());
if (fileName.indexOf(",") >= 0) {
filePath += fileName.substring(0, fileName.lastIndexOf(",") + 1).replaceAll(",", "/");
fileName = fileName.substring(fileName.lastIndexOf(",") + 1);
}
// if ("im".equalsIgnoreCase(type)) {
// type = "imfile";
// }
// else if (FileTypeEnum.ANNEXPIC.equalsIgnoreCase(type)) {
// type = FileTypeEnum.ANNEX;
// }
// 下载文件
byte[] bytes = FileUploadUtils.downloadFileByte(filePath, fileName, false);
FileDownloadUtil.flushImage(bytes, fileName);
}
/**
* 获取IM聊天图片
* 注意 后缀名前端故意把 .替换@
*
* @param fileName
* @return
*/
@NoDataSourceBind()
@Operation(summary = "获取IM聊天图片")
@GetMapping("/IMImage/{fileName}")
@Parameters({
@Parameter(name = "fileName", description = "名称", required = true),
})
public void imImage(@PathVariable("fileName") String fileName) {
byte[] bytes = FileUploadUtils.downloadFileByte(configValueUtil.getImContentFilePath(), fileName, false);
FileDownloadUtil.flushImage(bytes, fileName);
}
/**
* 查看图片
*
* @param type 哪个文件夹
* @param fileName 文件名称
* @return
*/
@NoDataSourceBind()
@Operation(summary = "查看图片")
@GetMapping("/{type}/{fileName}")
@Parameters({
@Parameter(name = "fileName", description = "名称", required = true),
@Parameter(name = "type", description = "类型", required = true),
})
public void img(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
// String filePath = configValueUtil.getBiVisualPath() + type + File.separator;
// if (StorageType.MINIO.equals(configValueUtil.getFileType())) {
// fileName = "/" + type + "/" + fileName;
// filePath = configValueUtil.getBiVisualPath().substring(0,
// configValueUtil.getBiVisualPath().length() - 1);
// }
String filePath = FilePathUtil.getFilePath(type.toLowerCase());
if (fileName.indexOf(",") >= 0) {
filePath += fileName.substring(0, fileName.lastIndexOf(",") + 1).replaceAll(",", "/");
fileName = fileName.substring(fileName.lastIndexOf(",") + 1);
}
// 下载文件
byte[] bytes = FileUploadUtils.downloadFileByte(filePath, fileName, false);
FileDownloadUtil.flushImage(bytes, fileName);
}
/**
* 获取IM聊天语音
* 注意 后缀名前端故意把 .替换@
*
* @param fileName
* @return
*/
@NoDataSourceBind()
@Operation(summary = "获取IM聊天语音")
@GetMapping("/IMVoice/{fileName}")
@Parameters({
@Parameter(name = "fileName", description = "名称", required = true),
})
public void imVoice(@PathVariable("fileName") String fileName) {
fileName = fileName.replaceAll("@", ".");
byte[] bytes = FileUploadUtils.downloadFileByte(configValueUtil.getImContentFilePath(), fileName, false);
FileDownloadUtil.flushImage(bytes, fileName);
}
/**
* app启动获取信息
*
* @param appName
* @return
*/
@NoDataSourceBind()
@Operation(summary = "app启动获取信息")
@GetMapping("/AppStartInfo/{appName}")
@Parameters({
@Parameter(name = "appName", description = "名称", required = true),
})
public ActionResult getAppStartInfo(@PathVariable("appName") String appName) {
appName = XSSEscape.escape(appName);
JSONObject object = new JSONObject();
object.put("AppVersion", configValueUtil.getAppVersion());
object.put("AppUpdateContent", configValueUtil.getAppUpdateContent());
return ActionResult.success(object);
}
// ----------大屏图片下载---------
@NoDataSourceBind()
@Operation(summary = "获取图片")
@GetMapping("/VisusalImg/{bivisualpath}/{type}/{fileName}")
@Parameters({
@Parameter(name = "type", description = "类型", required = true),
@Parameter(name = "bivisualpath", description = "路径", required = true),
@Parameter(name = "fileName", description = "名称", required = true),
})
public void downVisusalImg(@PathVariable("type") String type, @PathVariable("bivisualpath") String bivisualpath,
@PathVariable("fileName") String fileName) {
fileName = XSSEscape.escape(fileName);
String filePath = configValueUtil.getBiVisualPath();
byte[] bytes = FileUploadUtils.downloadFileByte(filePath + type + "/", fileName, false);
FileDownloadUtil.flushImage(bytes, fileName);
}
// ----------------------
@NoDataSourceBind()
@Operation(summary = "预览文件")
@GetMapping("/Uploader/Preview")
public ActionResult Preview(PreviewParams previewParams) {
// 读取允许文件预览类型
String allowPreviewType = configValueUtil.getAllowPreviewFileType();
String[] fileType = allowPreviewType.split(",");
String fileName = XSSEscape.escape(previewParams.getFileName());
// 文件预览类型检验
String docType = fileName.substring(fileName.lastIndexOf(".") + 1);
String s = Arrays.asList(fileType).stream().filter(type -> type.equals(docType)).findFirst().orElse(null);
if (StringUtil.isEmpty(s)) {
return ActionResult.fail(MsgCode.FA040.get());
}
// 解析文件url 获取类型
String type = configValueUtil.getWebAnnexFilePath();
String fileNameAll = previewParams.getFileDownloadUrl();
if (!StringUtil.isEmpty(fileNameAll)) {
String[] data = fileNameAll.split("/");
type = data.length > 4 ? data[4] : "";
}
String url;
// 文件预览策略
if ("yozo".equals(configValueUtil.getPreviewType())) {
if (StringUtil.isEmpty(previewParams.getFileVersionId())) {
return ActionResult.fail(MsgCode.FA041.get());
}
String fileVersionId = XSSEscape.escape(previewParams.getFileVersionId());
// 获取签名
Map<String, String[]> parameter = new HashMap<String, String[]>();
parameter.put("appId", new String[] { YozoParams.APP_ID });
parameter.put("fileVersionId", new String[] { fileVersionId });
String sign = yozoUtils.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, parameter).getData();
url = "http://eic.yozocloud.cn/api/view/file?fileVersionId="
+ fileVersionId
+ "&appId="
+ YozoParams.APP_ID
+ "&sign="
+ sign;
} else {
if (FileUploadUtils.getDefaultPlatform().startsWith("local-plus")) {
url = YozoParams.YUNZHUPAAS_DOMAINS + "/api/file/filedownload/" + type + "/"
+ previewParams.getFileName();
} else {
// 图像格式
if ("jpg,gif,png,bmp,jpeg".contains(docType)) {
url = YozoParams.YUNZHUPAAS_DOMAINS + "/api/file/filedownload/" + type;
} else {
String[] split = fileNameAll.split("/");
if (split.length > 5) {
type = FilePathUtil.getFilePath(type) + split[5].replaceAll(",", "/");
}
FileDetail fileDetail = FileUploadUtils.getFileDetail(type, fileName, false);
url = FileUploadUtils.getDomain() + FileUploadUtils.getBucketName() + fileDetail.getBasePath()
+ fileDetail.getPath();
}
}
// encode编码
String fileUrl = Base64.encodeBase64String(url.getBytes());
url = configValueUtil.getKkFileUrl() + "onlinePreview?url=" + fileUrl;
}
return ActionResult.success(MsgCode.SU000.get(), url);
}
@NoDataSourceBind()
@Operation(summary = "kk本地文件预览")
@GetMapping("/filedownload/{type}/{fileName}")
public void filedownload(@PathVariable("type") String type, @PathVariable("fileName") String fileName,
HttpServletResponse response) {
String typePath = FilePathUtil.getFilePath(type);
if (fileName.indexOf(",") >= 0) {
typePath += fileName.substring(0, fileName.lastIndexOf(",") + 1).replaceAll(",", "/");
fileName = fileName.substring(fileName.lastIndexOf(",") + 1);
}
String tmpPath = typePath + fileName;
boolean b = FileUtil.fileIsFile(tmpPath);
if (!b) {
FileUploadUtils.downLocal(FilePathUtil.getFilePath(type), FileUploadUtils.getLocalBasePath() + typePath,
fileName);
}
String filePath = XSSEscape.escapePath(FileUploadUtils.getLocalBasePath() + typePath + fileName);
OutputStream os = null;
// 本地取对应文件
File file = new File(filePath);
try {
os = response.getOutputStream();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Dispostion",
"attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
@Cleanup
FileInputStream fileInputStream = new FileInputStream(file);
@Cleanup
WritableByteChannel writableByteChannel = Channels.newChannel(os);
@Cleanup
FileChannel channel = fileInputStream.getChannel();
channel.transferTo(0, channel.size(), writableByteChannel);
channel.close();
os.flush();
writableByteChannel.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Operation(summary = "分片上传获取")
@GetMapping("/chunk")
public ActionResult checkChunk(Chunk chunk) {
String type = chunk.getExtension();
if (!OptimizeUtil.fileType(configValueUtil.getAllowUploadFileType(), type)) {
return ActionResult.fail(MsgCode.FA017.get());
}
String identifier = chunk.getIdentifier();
String path = configValueUtil.getTemporaryFilePath();
String filePath = XSSEscape.escapePath(path + identifier);
List<File> chunkFiles = FileUtil.getFile(new File(FileUploadUtils.getLocalBasePath() + filePath));
List<Integer> existsChunk = chunkFiles.stream().filter(f -> {
if (f.getName().endsWith(".tmp")) {
FileUtils.deleteQuietly(f);
} else
return f.getName().startsWith(identifier);
return false;
}).map(f -> Integer.parseInt(f.getName().replace(identifier.concat("-"), ""))).collect(Collectors.toList());
ChunkRes chunkRes = ChunkRes.builder().merge(chunk.getTotalChunks().equals(existsChunk.size()))
.chunkNumbers(existsChunk).build();
return ActionResult.success(chunkRes);
}
@Operation(summary = "分片上传附件")
@PostMapping("/chunk")
public ActionResult upload(Chunk chunk, @RequestParam("file") MultipartFile file) {
String type = chunk.getExtension();
if (!OptimizeUtil.fileType(configValueUtil.getAllowUploadFileType(), type)) {
return ActionResult.fail(MsgCode.FA017.get());
}
ChunkRes chunkRes = ChunkRes.builder().build();
chunkRes.setMerge(false);
File chunkFile = null;
File chunkTmpFile = null;
try {
String filePath = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
Integer chunkNumber = chunk.getChunkNumber();
String identifier = XSSEscape.escapePath(chunk.getIdentifier());
String chunkTempPath = XSSEscape.escapePath(filePath + identifier);
File path = new File(chunkTempPath);
if (!path.exists()) {
path.mkdirs();
}
String chunkName = XSSEscape.escapePath(identifier.concat("-") + chunkNumber);
String chunkTmpName = XSSEscape.escapePath(chunkName.concat(".tmp"));
chunkFile = new File(chunkTempPath, chunkName);
chunkTmpFile = new File(chunkTempPath, chunkTmpName);
if (chunkFile.exists() && chunkFile.length() == chunk.getCurrentChunkSize()) {
System.out.println("该分块已经上传:" + chunkFile.getName());
} else {
@Cleanup
InputStream inputStream = file.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, chunkTmpFile);
chunkTmpFile.renameTo(chunkFile);
}
int existsSize = (int) FileUtil.getFile(new File(chunkTempPath)).stream()
.filter(f -> f.getName().startsWith(identifier) && !f.getName().endsWith(".tmp")).count();
chunkRes.setMerge(Objects.equals(existsSize, chunk.getTotalChunks()));
} catch (Exception e) {
try {
FileUtils.deleteQuietly(chunkTmpFile);
FileUtils.deleteQuietly(chunkFile);
} catch (Exception ee) {
e.printStackTrace();
}
System.out.println("上传异常:" + e);
return ActionResult.fail(MsgCode.FA033.get());
}
return ActionResult.success(chunkRes);
}
@Operation(summary = "分片组装")
@PostMapping("/merge")
public ActionResult merge(MergeChunkDto mergeChunkDto) {
String identifier = XSSEscape.escapePath(mergeChunkDto.getIdentifier());
String path = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
String filePath = XSSEscape.escapePath(path + identifier);
String uuid = RandomUtil.uuId();
String partFile = XSSEscape.escapePath(path + uuid + "." + mergeChunkDto.getExtension());
UploaderVO vo = UploaderVO.builder().build();
try {
List<File> mergeFileList = FileUtil.getFile(new File(filePath));
@Cleanup
FileOutputStream destTempfos = new FileOutputStream(partFile, true);
for (int i = 0; i < mergeFileList.size(); i++) {
String chunkName = identifier.concat("-") + (i + 1);
File files = new File(filePath, chunkName);
if (files.exists()) {
FileUtils.copyFile(files, destTempfos);
}
}
File partFiles = new File(partFile);
if (partFiles.exists()) {
MultipartFile multipartFile = FileUtil.createFileItem(partFiles);
String type = mergeChunkDto.getType();
PathTypeModel pathTypeModel = new PathTypeModel();
pathTypeModel.setPathType(mergeChunkDto.getPathType());
pathTypeModel.setSortRule(mergeChunkDto.getSortRule());
pathTypeModel.setTimeFormat(mergeChunkDto.getTimeFormat());
pathTypeModel.setFolder(mergeChunkDto.getFolder());
if ("selfPath".equals(pathTypeModel.getPathType())) {
if (StringUtil.isNotEmpty(pathTypeModel.getFolder())) {
String folder = pathTypeModel.getFolder();
folder = folder.replaceAll("\\\\", "/");
// String regex = "^[a-z0-9A-Z\\u4e00-\\u9fa5\\\\\\/]+$";
// 文件夹名以字母或数字开头由字母、数字、下划线和连字符组成长度不超过100个字符
String regex = "^[a-zA-Z0-9][a-zA-Z0-9_\\-\\\\\\/]{0,99}$";
if (!folder.matches(regex)) {
return ActionResult.fail(MsgCode.FA038.get());
}
}
}
vo = uploaderVO(multipartFile, type, pathTypeModel);
FileUtil.deleteTmp(multipartFile);
}
} catch (Exception e) {
log.error("合并分片失败: {}", e.getMessage());
throw new DataException(MsgCode.FA033.get());
} finally {
FileUtils.deleteQuietly(new File(filePath));
FileUtils.deleteQuietly(new File(partFile));
}
return ActionResult.success(vo);
}
/**
* 封装上传附件
*
* @param file
* @param type
* @return
* @throws IOException
*/
private UploaderVO uploaderVO(MultipartFile file, String type, PathTypeModel pathTypeModel) throws IOException {
String orgFileName = file.getOriginalFilename();
String fileType = UpUtil.getFileType(file);
// if (OptimizeUtil.fileSize(file.getSize(), 1024000)) {
// return ActionResult.fail("上传失败文件大小超过1M");
// }
// if ("mail".equals(type)) {
// type = "temporary";
// }
// 实际文件名
String fileName = DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + "." + fileType;
// 文件上传路径
String filePath = FilePathUtil.getFilePath(type.toLowerCase());
// 文件自定义路径相对路径
String relativeFilePath = "";
if ("selfPath".equals(pathTypeModel.getPathType()) && pathTypeModel.getSortRule() != null) {
// 按路径规则顺序构建生成目录
String sortRule = pathTypeModel.getSortRule();
List<String> rules = null;
if (sortRule.contains("[")) {
rules = JsonUtil.getJsonToList(sortRule, String.class);
} else {
rules = Arrays.asList(pathTypeModel.getSortRule().split(","));
}
for (String rule : rules) {
// 按用户存储
if ("1".equals(rule)) {
UserInfo userInfo = UserProvider.getUser();
relativeFilePath += userInfo.getUserAccount() + "/";
}
// 按照时间格式
else if (StringUtil.isNotEmpty(pathTypeModel.getTimeFormat()) && "2".equals(rule)) {
String timeFormat = pathTypeModel.getTimeFormat();
timeFormat = timeFormat.replaceAll("YYYY", "yyyy");
timeFormat = timeFormat.replaceAll("DD", "dd");
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(timeFormat);
String currentDateStr = currentDate.format(formatter);
relativeFilePath += currentDateStr;
if (!currentDateStr.endsWith("/")) {
relativeFilePath += "/";
}
}
// 按自定义目录
else if (StringUtil.isNotEmpty(pathTypeModel.getFolder()) && "3".equals(rule)) {
String folder = pathTypeModel.getFolder();
folder = folder.replaceAll("\\\\", "/");
relativeFilePath += folder;
if (!folder.endsWith("/")) {
relativeFilePath += "/";
}
}
}
if (StringUtil.isNotEmpty(relativeFilePath)) {
relativeFilePath = StringUtil.replaceMoreStrToOneStr(relativeFilePath, "/");
if (relativeFilePath.startsWith("/")) {
relativeFilePath = relativeFilePath.substring(1);
}
filePath += relativeFilePath;
fileName = relativeFilePath.replaceAll("/", ",") + fileName;
}
}
UploaderVO vo = UploaderVO.builder().fileSize(file.getSize()).fileExtension(fileType).build();
FileInfo fileInfo = FileUploadUtils.uploadFile(file, filePath, fileName);
fileName = fileInfo.getFilename();
String thFilename = fileInfo.getThFilename();
if (!StringUtil.isNotEmpty(thFilename)) {
// 小图没有压缩直接用原图
thFilename = fileName;
}
// 自定义文件实际文件名
if (StringUtil.isNotEmpty(relativeFilePath)) {
fileName = relativeFilePath.replaceAll("/", ",") + fileName;
thFilename = relativeFilePath.replaceAll("/", ",") + thFilename;
}
vo.setName(fileName);
// UploadUtil.uploadFile(configValueUtil.getFileType(), type, fileName, file,
// filePath);
if ("useravatar".equalsIgnoreCase(type)) {
vo.setUrl(UploaderUtil.uploaderImg(fileName));
vo.setUrl(UploaderUtil.uploaderImg(thFilename));
} else if ("annex".equalsIgnoreCase(type)) {
// UserInfo userInfo = UserProvider.getUser();
// vo.setUrl(UploaderUtil.uploaderFile(userInfo.getId() + "#" + fileName + "#" +
// type));
vo.setUrl(UploaderUtil.uploaderImg("/api/file/Image/annex/", fileName));
vo.setThumbUrl(UploaderUtil.uploaderImg("/api/file/Image/annex/", thFilename));
} else if ("annexpic".equalsIgnoreCase(type)) {
vo.setUrl(UploaderUtil.uploaderImg("/api/file/Image/annexpic/", fileName));
vo.setThumbUrl(UploaderUtil.uploaderImg("/api/file/Image/annexpic/", thFilename));
} else {
vo.setUrl(UploaderUtil.uploaderImg("/api/file/Image/" + type.toLowerCase() + "/", fileName));
vo.setThumbUrl(UploaderUtil.uploaderImg("/api/file/Image/" + type.toLowerCase() + "/", thFilename));
}
// 上传到永中
if ("yozo".equals(configValueUtil.getPreviewType())) {
try {
@Cleanup
InputStream inputStream = file.getInputStream();
String s = yozoUtils.uploadFileInPreview(inputStream, orgFileName);
Map<String, Object> map = JsonUtil.stringToMap(s);
if ("操作成功".equals(map.get("message"))) {
Map<String, Object> dataMap = JsonUtil.stringToMap(String.valueOf(map.get("data")));
String verId = String.valueOf(dataMap.get("fileVersionId"));
vo.setFileVersionId(verId);
}
} catch (Exception e) {
System.out.println("上传到永中失败");
e.printStackTrace();
}
}
return vo;
}
public static void main(String[] args) {
String path = "../../../windows/win.ini|userAvatar/../../../../windows/win.ini";
System.out.printf(XSSEscape.escapePath(path));
}
}

View File

@@ -0,0 +1,307 @@
package com.yunzhupaas.controller;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.entity.FileEntity;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.model.FileForm;
import com.yunzhupaas.model.UploaderVO;
import com.yunzhupaas.model.YozoFileParams;
import com.yunzhupaas.model.YozoParams;
import com.yunzhupaas.service.YozoService;
import com.yunzhupaas.util.FileUtil;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.XSSEscape;
import com.yunzhupaas.util.wxutil.HttpUtil;
import com.yunzhupaas.utils.YozoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* @author 云筑产品开发平台组
*/
@RestController
@RequestMapping
@Tag(name = "在线文档预览", description = "文件在线预览")
public class YozoFileController {
@Autowired
private YozoService yozoService;
@Autowired
private YozoUtils yozoUtil;
@Autowired
private ConfigValueUtil configValueUtil;
@PostMapping("/api/file/getViewUrlWebPath")
@Operation(summary = "文档预览")
public ActionResult getUrl(YozoFileParams params) {
String previewUrl = XSSEscape.escape(yozoService.getPreviewUrl(params));
return ActionResult.success("success", previewUrl);
}
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上传本地文件")
public ActionResult upload(@RequestPart("multipartFile") MultipartFile file) throws IOException {
String result = yozoUtil.uploadFileInPreview(file.getInputStream(),file.getOriginalFilename());
String fileName = file.getOriginalFilename();
UploaderVO vo = UploaderVO.builder().name(fileName).build();
Map<String, Object> map = JsonUtil.stringToMap(result);
if ("操作成功".equals(map.get("message"))){
Map<String, Object> dataMap = JsonUtil.stringToMap(String.valueOf(map.get("data")));
String verId = String.valueOf(dataMap.get("fileVersionId"));
vo.setFileVersionId(verId);
return ActionResult.success("Success",vo);
}
return ActionResult.fail(MsgCode.FA033.get());
}
/**
*
* @param fileName 新建文件名
* @param templateType (模板类型1新建doc文档2新建docx文档3新建ppt文档4新建pptx文档5新建xls文档6新建xlsx文档)
* @return
*/
@GetMapping("/newCreate")
@Operation(summary = "新建文件")
@Parameters({
@Parameter(name = "fileName", description = "名称"),
@Parameter(name = "templateType", description = "类型"),
})
public ActionResult newCreate(@RequestParam("fileName") String fileName, @RequestParam("templateType") String templateType) {
String fileNa = yozoUtil.getFileName(fileName, templateType);
if (fileNa == null) {
return ActionResult.fail(MsgCode.FA042.get());
}
//判断文件是否创建过
FileEntity fileEntity = yozoService.selectByName(fileNa);
if (fileEntity != null) {
return ActionResult.fail(MsgCode.FA043.get());
}
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("templateType", new String[]{templateType});
params.put("fileName", new String[]{fileName});
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
String url = YozoParams.CLOUD_DOMAIN + "/api/file/template?templateType=" + templateType +
"&fileName=" + fileName +
"&appId=" + YozoParams.APP_ID +
"&sign=" + sign;
String s = HttpUtil.sendHttpPost(url);
Map<String, Object> maps = JSONObject.parseObject(s, Map.class);
Map<String, String> fileMap = (Map<String, String>) maps.get("data");
String fileVersionId = fileMap.get("fileVersionId");
String fileId = fileMap.get("fileId");
ActionResult back = yozoService.saveFileId(fileVersionId, fileId, fileNa);
//在本地新建文件
FileUtil.createFile(configValueUtil.getDocumentPreviewPath(), fileNa);
return back;
}
@GetMapping("/uploadByHttp")
@Operation(summary = "http上传文件")
@Parameters({
@Parameter(name = "fileUrl", description = "路径"),
})
public ActionResult uploadByHttp(@RequestParam("fileUrl") String fileUrl) {
//获取签名
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("fileUrl", new String[]{fileUrl});
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
String url = YozoParams.CLOUD_DOMAIN + "/api/file/http?fileUrl=" + fileUrl +
"&appId=" + YozoParams.APP_ID +
"&sign=" + sign;
String s = HttpUtil.sendHttpPost(url);
Map<String, Object> maps = JSONObject.parseObject(s, Map.class);
Map<String, String> fileMap = (Map<String, String>) maps.get("data");
String fileVersionId = fileMap.get("fileVersionId");
String fileId = fileMap.get("fileId");
ActionResult back = yozoService.saveFileIdByHttp(fileVersionId, fileId, fileUrl);
return back;
}
@GetMapping("/downloadFile")
@Operation(summary = "永中下载文件")
@Parameters({
@Parameter(name = "fileVersionId", description = "主键"),
})
public String downloadFile(@RequestParam("fileVersionId") String fileVersionId) {
String newFileVersionId = XSSEscape.escape(fileVersionId);
FileEntity fileEntity = yozoService.selectByVersionId(newFileVersionId);
if (fileEntity == null) {
return MsgCode.FA044.get();
}
//获取签名
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("fileVersionId", new String[]{newFileVersionId});
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
String url = YozoParams.CLOUD_DOMAIN + "/api/file/download?fileVersionId=" + newFileVersionId +
"&appId=" + YozoParams.APP_ID +
"&sign=" + sign;
return url;
}
@GetMapping("/deleteVersionFile")
@Operation(summary = "删除文件版本")
@Parameters({
@Parameter(name = "fileVersionId", description = "主键"),
})
public ActionResult deleteVersion(@RequestParam("fileVersionId") String fileVersionId) {
//获取签名
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("fileVersionId", new String[]{fileVersionId});
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
String url = YozoParams.CLOUD_DOMAIN + "/api/file/delete/version?fileVersionId=" + fileVersionId +
"&appId=" + YozoParams.APP_ID +
"&sign=" + sign;
String s = HttpUtil.sendHttpGet(url);
Map<String, Object> maps = JSONObject.parseObject(s, Map.class);
String fileName = yozoService.selectByVersionId(fileVersionId).getFileName();
String path = configValueUtil.getDocumentPreviewPath() + fileName;
if (FileUtil.fileIsFile(path)) {
File file = new File(XSSEscape.escapePath(path));
file.delete();
}
String versionId = (String) maps.get("data");
ActionResult back = yozoService.deleteFileByVersionId(versionId);
return back;
}
@GetMapping("/batchDelete")
@Operation(summary = "批量删除文件版本")
@Parameters({
@Parameter(name = "fileVersionIds", description = "主键"),
})
public ActionResult batchDelete(@RequestParam("fileVersionIds") String[] fileVersionIds) {
List<String> asList = new ArrayList<>(16);
//获取签名
for (String fileVersionId : fileVersionIds) {
String escape = XSSEscape.escape(fileVersionId);
asList.add(escape);
}
String[] newFileVersionIds = asList.toArray(fileVersionIds);
Map<String, String[]> params = new HashMap<>();
params.put("fileVersionIds", newFileVersionIds);
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
StringBuilder fileVersionIdList = new StringBuilder();
for (String s : newFileVersionIds) {
String fileName = yozoService.selectByVersionId(s).getFileName();
String path = configValueUtil.getDocumentPreviewPath() + fileName;
File file = new File(XSSEscape.escapePath(path));
file.delete();
fileVersionIdList.append("fileVersionIds=" + s + "&");
}
String list = fileVersionIdList.toString();
String url = YozoParams.CLOUD_DOMAIN + "/api/file/delete/versions?" + list +
"appId=" + YozoParams.APP_ID +
"&sign=" + sign;
String s = HttpUtil.sendHttpGet(url);
ActionResult back = yozoService.deleteBatch(newFileVersionIds);
return back;
}
@GetMapping("/editFile")
@Operation(summary = "在线编辑")
@Parameters({
@Parameter(name = "fileVersionId", description = "主键"),
})
public ActionResult editFile(@RequestParam("fileVersionId") String fileVersionId) {
String newFileVersionId = XSSEscape.escape(fileVersionId);
//获取签名
Map<String, String[]> params = new HashMap<>();
params.put("fileVersionId", new String[]{newFileVersionId});
String sign = yozoUtil.generateSign(YozoParams.APP_ID, YozoParams.APP_KEY, params).getData();
String url = YozoParams.EDIT_DOMAIN + "/api/edit/file?fileVersionId=" + newFileVersionId +
"&appId=" + YozoParams.APP_ID +
"&sign=" + sign;
return ActionResult.success("success", url);
}
/**
* 永中回调
*
* @param oldFileId
* @param newFileId
* @param message
* @param errorCode
* @return
*/
@PostMapping("/3rd/edit/callBack")
@Parameters({
@Parameter(name = "oldFileId", description = "主键"),
@Parameter(name = "newFileId", description = "主键"),
@Parameter(name = "message", description = "消息"),
@Parameter(name = "errorCode", description = "编码"),
})
public Map<String, Object> editCallBack(@RequestParam("oldFileId") String oldFileId, @RequestParam("newFileId") String newFileId, @RequestParam("message") String message, @RequestParam("errorCode") Integer errorCode) {
String escapeOldFileId = XSSEscape.escape(oldFileId);
String escapeNewFileId = XSSEscape.escape(newFileId);
String escapeMessage = XSSEscape.escape(message);
yozoService.editFileVersion(escapeOldFileId, escapeNewFileId);
Map<String, Object> result = new HashMap<>();
result.put("oldFileId", escapeOldFileId);
result.put("newFileId", escapeNewFileId);
result.put("message", escapeMessage);
result.put("errorCode", errorCode);
return result;
}
@PostMapping("/documentList")
@Operation(summary = "文档列表")
@Parameters({
@Parameter(name = "pageModel", description = "分页模型", required = true),
})
public ActionResult documentList(@RequestBody PaginationVO pageModel) {
PaginationVO pv = new PaginationVO();
pv.setCurrentPage(pageModel.getCurrentPage());
pv.setPageSize(pageModel.getPageSize());
pv.setTotal(pageModel.getTotal());
List<FileEntity> list = yozoService.getAllList(pv);
List<FileForm> listVo = JsonUtil.getJsonToList(list, FileForm.class);
return ActionResult.page(listVo, pv);
}
/**
* 传入新的fileVersionId同步
*
* @param fileVersionId
* @return
* @throws Exception
*/
@GetMapping("/updateFile")
@Operation(summary = "/同步文件版本到本地")
@Parameters({
@Parameter(name = "fileVersionId", description = "主键"),
})
public ActionResult updateFile(@RequestParam("fileVersionId") String fileVersionId) throws Exception {
FileEntity fileEntity = yozoService.selectByVersionId(fileVersionId);
String fileName = fileEntity.getFileName();
String path = configValueUtil.getDocumentPreviewPath() + fileName;
if (FileUtil.fileIsFile(path)) {
File file = new File(XSSEscape.escapePath(path));
file.delete();
}
String fileUrl = this.downloadFile(fileVersionId);
yozoUtil.downloadFile(fileUrl, path);
return ActionResult.success(MsgCode.SU004.get());
}
}

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yunzhupaas-file</artifactId>
<groupId>com.yunzhupaas</groupId>
<version>5.2.0-RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yunzhupaas-file-entity</artifactId>
<dependencies>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common-all</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,44 @@
package com.yunzhupaas.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.yunzhupaas.base.entity.SuperExtendEntity;
import lombok.Data;
/**
* @author YUNZHUPAAS
*/
@Data
@TableName("base_file")
public class FileEntity extends SuperExtendEntity<String> {
/**
* 文件编辑版本
*/
@TableField("f_file_version")
private String fileVersionId;
/**
* 文件名
*/
@TableField("f_file_name")
private String fileName;
/**
* 文件上传方式
*/
@TableField("f_type")
private String type;
/**
* 上传的url
*/
@TableField("f_url")
private String url;
/**
* 上次文件版本
*/
@TableField("f_old_file_version_id")
private String oldFileVersionId;
}

View File

@@ -0,0 +1,25 @@
package com.yunzhupaas.enums;
/**
* 文件预览方式
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/6
*/
public enum FilePreviewTypeEnum {
/**
* yozo:永中预览; doc:kk文档预览;
*/
YOZO_ONLINE_PREVIEW("yozoOnlinePreview"),
LOCAL_PREVIEW("localPreview");
FilePreviewTypeEnum(String type) {
this.type = type;
}
private String type;
public String getType() {
return type;
}
}

View File

@@ -0,0 +1,60 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
@Data
public class Chunk implements Serializable {
/**
* 当前文件块从1开始
*/
@Schema(description = "当前文件块")
private Integer chunkNumber;
/**
* 分块大小
*/
@Schema(description = "分块大小")
private Long chunkSize;
/**
* 当前分块大小
*/
@Schema(description = "当前分块大小")
private Long currentChunkSize;
/**
* 总大小
*/
@Schema(description = "总大小")
private Long totalSize;
/**
* 文件标识
*/
@Schema(description = "文件标识")
private String identifier;
/**
* 文件名
*/
@Schema(description = "文件名")
private String fileName;
/**
* 相对路径
*/
@Schema(description = "相对路径")
private String relativePath;
/**
* 总块数
*/
@Schema(description = "总块数")
private Integer totalChunks;
/**
* 文件类型
*/
@Schema(description = "文件类型")
private String type;
private String extension;
private String fileType;
}

View File

@@ -0,0 +1,25 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: 分片上传响应
* @date 2024/6/10 20:59
*/
@Data
@Builder
public class ChunkRes implements Serializable {
@Schema(description = "块数")
private List<Integer> chunkNumbers = new ArrayList<>();
@Schema(description = "是否合并")
private Boolean merge;
}

View File

@@ -0,0 +1,19 @@
package com.yunzhupaas.model;
import lombok.Data;
/**
*
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/14
*/
@Data
public class FileForm {
private String fileId;
private String fileVersionId;
private String fileName;
}

View File

@@ -0,0 +1,14 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class LanguageVO {
@Schema(description ="语言编码")
private String encode;
@Schema(description ="语言名称")
private String fullName;
}

View File

@@ -0,0 +1,54 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* @Description:
* @date 2024/6/10 20:39
*/
@Data
public class MergeChunkDto implements Serializable {
@Schema(description = "名称")
private String fileName;
@Schema(description = "分片")
private String identifier;
@Schema(description = "文件大小")
private Long filesize;
@Schema(description = "扩展")
private String extension;
@Schema(description = "文件类型")
private String fileType;
@Schema(description = "类型")
private String type;
@Schema(description = "父级id")
private String parentId;
/**
* 文件上传路径类型
*/
@Schema(description = "文件上传路径类型")
private String pathType;
@Schema(description = "文件上传路径规则")
private String sortRule;
@Schema(description = "时间存储格式")
private String timeFormat;
/**
* 文件路径,子级文件用“/”隔开文件1/文件1-1
*/
@Schema(description = "文件路径")
private String folder;
}

View File

@@ -0,0 +1,28 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 文件上传路径配置模型
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2024-07-26
*/
@Data
public class PathTypeModel implements Serializable{
private String pathType;
private String sortRule;
private String timeFormat;
private String folder;
}

View File

@@ -0,0 +1,23 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
*
*
* @author 云筑产品开发平台组
* @version V3.3
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2022/3/30
*/
@Data
public class PreviewParams {
@Schema(description = "文件名")
private String fileName;
@Schema(description = "预览文件id")
private String fileVersionId;
@Schema(description = "文件下载路径")
private String fileDownloadUrl;
}

View File

@@ -0,0 +1,50 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 预览文件相关参数
*
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司http://www.szlecheng.cn
* @date 2021/5/6
*/
@Data
public class SuffixParams {
/**
* 是否强制重新转换(忽略缓存),true为强制重新转换false为不强制重新转换。
*/
@Schema(description = "是否强制重新转换")
private Boolean noCache;
/**
* 针对单文档设置水印内容。
*/
@Schema(description = "设置水印内容")
private String watermark;
/**
* 0否1是默认为0。针对单文档设置是否防复制
*/
@Schema(description = "是否防复制")
private Integer isCopy;
/**
* 试读功能(转换页数的起始页和转换页数的终止页,拥有对应权限的域名才能调用)
*/
@Schema(description = "开始")
private Integer pageStart;
@Schema(description = "结束")
private Integer pageEnd;
/**
* 用于无文件后缀链接,指定预览文件后缀名
*/
@Schema(description = "文件后缀链接")
private String type;
}

View File

@@ -0,0 +1,24 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class UploaderVO {
@Schema(description ="名称")
private String name;
@Schema(description ="请求接口")
private String url;
@Schema(description ="预览文件id")
private String fileVersionId;
@Schema(description ="文件大小")
private Long fileSize;
@Schema(description ="文件后缀")
private String fileExtension;
@Schema(description ="缩略图")
private String thumbUrl;
}

View File

@@ -0,0 +1,47 @@
package com.yunzhupaas.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* @author YUNZHUPAAS
*/
@Data
public class YozoFileParams {
@Schema(description = "路径")
private String url;
/**
* 是否强制重新转换(忽略缓存),true为强制重新转换false为不强制重新转换。
*/
@Schema(description = "是否强制重新转换")
private Boolean noCache;
/**
* 针对单文档设置水印内容。
*/
@Schema(description = "设置水印内容")
private String watermark;
/**
* 0否1是默认为0。针对单文档设置是否防复制
*/
@Schema(description = "是否防复制")
private Integer isCopy;
/**
* 试读功能(转换页数的起始页和转换页数的终止页,拥有对应权限的域名才能调用)
*/
@Schema(description = "开始")
private Integer pageStart;
@Schema(description = "结束")
private Integer pageEnd;
/**
* 用于无文件后缀链接,指定预览文件后缀名
*/
@Schema(description = "文件后缀链接")
private String type;
}

View File

@@ -0,0 +1,54 @@
package com.yunzhupaas.model;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author YUNZHUPAAS
*/
@Data
@Component
public class YozoParams implements InitializingBean {
@Value("${config.YozoDomainKey}")
private String domainKey;
@Value("${config.YozoDomain}")
private String domain;
@Value("${config.YozoCloudDomain}")
private String cloudDomain;
@Value("${config.YozoAppId}")
private String appId;
@Value("${config.YozoAppKey}")
private String appKey;
@Value("${config.YozoEditDomain}")
private String editDomain;
@Value("${config.ApiDomain}")
private String yunzhupaasDomain;
public static String DOMAIN_KEY;
public static String DOMAIN;
public static String CLOUD_DOMAIN;
public static String APP_ID;
public static String APP_KEY;
public static String EDIT_DOMAIN;
public static String YUNZHUPAAS_DOMAINS;
@Override
public void afterPropertiesSet() throws Exception {
DOMAIN = domain;
DOMAIN_KEY = domainKey;
CLOUD_DOMAIN = cloudDomain;
APP_ID = appId;
APP_KEY = appKey;
EDIT_DOMAIN = editDomain;
YUNZHUPAAS_DOMAINS = yunzhupaasDomain;
}
}

View File

@@ -0,0 +1,45 @@
package com.yunzhupaas.utils;
import com.yunzhupaas.model.YozoFileParams;
import com.yunzhupaas.model.YozoParams;
import com.yunzhupaas.util.XSSEscape;
import org.springframework.util.StringUtils;
/**
* @author 云筑产品开发平台组
*/
public class SplicingUrlUtil {
/**
* 永中预览url拼接
* @param params
* @return
*/
public static String getPreviewUrl(YozoFileParams params) {
StringBuilder paramsUrl = new StringBuilder();
if (!StringUtils.isEmpty(params.getNoCache())) {
paramsUrl.append("&noCache=" + params.getNoCache());
}
if (!StringUtils.isEmpty(params.getWatermark())) {
String watermark = XSSEscape.escape(params.getWatermark());
paramsUrl.append("&watermark=" + watermark);
}
if (!StringUtils.isEmpty(params.getIsCopy())) {
paramsUrl.append("&isCopy=" + params.getIsCopy());
}
if (!StringUtils.isEmpty(params.getPageStart())) {
paramsUrl.append("&pageStart=" + params.getPageStart());
}
if (!StringUtils.isEmpty(params.getPageEnd())) {
paramsUrl.append("&pageEnd=" + params.getPageEnd());
}
if (!StringUtils.isEmpty(params.getType())) {
String type = XSSEscape.escape(params.getType());
paramsUrl.append("&type=" + type);
}
String s = paramsUrl.toString();
String previewUrl= YozoParams.DOMAIN+"?k=" + YozoParams.DOMAIN_KEY + "&url=" + params.getUrl() + s;
return previewUrl;
}
}