lc/lc123/cloud/app/api/utils/AttachmentFileUtil.java

416 lines
17 KiB
Java
Raw Normal View History

2025-11-12 10:09:03 +00:00
package tqq9.lc123.cloud.app.api.utils;
import com.kingdee.bos.qinglightapp.util.SslUtils;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.entity.MainEntityType;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
2025-11-12 10:09:03 +00:00
import kd.bos.util.FileNameUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lxl
*/
public class AttachmentFileUtil {
private final static Log logger = LogFactory.getLog(AttachmentFileUtil.class);
2025-11-12 10:09:03 +00:00
/**
* 将Base64字符串转换为InputStream
*
* @param base64String Base64编码的字符串
* @return InputStream对象
* @throws IllegalArgumentException 如果Base64字符串格式无效
*/
public static InputStream toInputStream(String base64String) {
if (base64String == null || base64String.trim().isEmpty()) {
return new ByteArrayInputStream(new byte[0]);
}
try {
// 移除可能的空白字符和换行符
String cleanBase64 = base64String.replaceAll("\\s+", "");
// 解码Base64
byte[] decodedBytes = Base64.getDecoder().decode(cleanBase64);
// 创建InputStream
return new ByteArrayInputStream(decodedBytes);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("无效的Base64字符串", e);
}
}
/**
* @param entity 目标单据实体标识
* @param pk 目标数据id
* @param fileName 带存入文件名称
* @param base64Image base64文件流
* @param attachKey 附件面板标识
* @throws IOException
*/
public static Map<String, Object> saveUrlFile2Attchment( String entity, Object pk, String fileName, String base64Image, String attachKey) {
Map<String, Object> result = new HashMap<>();
// 示例Base64字符串
try (InputStream sourceFile = toInputStream(base64Image)) {
int sourceFileSize = sourceFile.available();
// 上传文件到缓存服务器
String tempPath = CacheFactory.getCommonCacheFactory().getTempFileCache().saveAsUrl(fileName, sourceFile, 7200);
if (tempPath.contains("tempfile/download.do?configKey")) {
//持久化附件到服务器
TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
InputStream in = cache.getInputStream(tempPath);
FileService service = FileServiceFactory.getAttachmentFileService();
FileService fs = FileServiceFactory.getAttachmentFileService();
RequestContext requestContext = RequestContext.get();
String uuid = UUID.randomUUID().toString().replace("-", "");
// 生成文件路径-上传附件时远程服务器需要存储文件的位置
String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
requestContext.getAccountId(), uuid, fileName);
FileItem fileItem = new FileItem(fileName, pathParam, in);
// cache.remove(url);
// 上传附件到文件服务器
tempPath =service.upload(fileItem);
}
//将文件缓存中的附件文件上传到正式文件服务器
// MainEntityType dataEntityType = MetadataServiceHelper.getDataEntityType(entity);
// String appId = dataEntityType.getAppId();
// String path = AttachmentServiceHelper.saveTempToFileService(tempPath, appId, entity, pk, fileName);
//创建附件
List<Map<String, Object>> attachItems = new ArrayList<>();
Map<String, Object> attachItem = new HashMap<>();
attachItem.put("name", fileName);
attachItem.put("size", sourceFileSize);
attachItem.put("uid", UUID.randomUUID().toString().replace("-", ""));
attachItem.put("url", tempPath);
attachItem.put("creator", UserServiceHelper.getCurrentUserId());
attachItem.put("lastModified", System.currentTimeMillis());
// attachItem.put("uid", uid1);
attachItems.add(attachItem);
//该方法仅处理数据记录不涉及文件存储。
AttachmentServiceHelper.upload(entity, pk, attachKey, attachItems);
} catch (Exception e) {
e.printStackTrace();
logger.info("附件上传失败,堆栈信息e:", e);
result.put("isSuccess", "false");
result.put("msg", "上传服务器异常:" + e);
return result;
}
result.put("isSuccess", "true");
result.put("msg", "附件上传成功");
return result;
}
/**
* @param entity 目标单据实体标识
* @param pk 目标数据id
* @param fileUrl 待存入文件的url
* @param fileName 带存入文件名称
* @param fileSize 带存入文件大小
2025-11-12 10:09:03 +00:00
* @param attachKey 附件面板标识
* @throws IOException
*/
public static Map<String, Object> saveUrlFile2Attchment(String uid1, String entity, Object pk, String fileUrl, String fileName, String fileSize, String attachKey) {
2025-11-12 10:09:03 +00:00
List<Map<String, Object>> attachments = new ArrayList<>();
Map<String, Object> attachItem = new HashMap<>();
Map<String, Object> result = new HashMap<>();
attachItem.put("name", fileName);
attachItem.put("uid", uid1);
InputStream inputStream = null;
HttpURLConnection conn = null;
String tempUrl = null;
try {
// 连接url并 获取输入流
// fileUrl = URLEncoder.encode(fileUrl,"UTF-8");
// fileUrl = java.net.URLDecoder.decode(fileUrl, "UTF-8");
fileUrl = encode(fileUrl, "UTF-8");
2025-11-12 10:09:03 +00:00
logger.info("fileUrl:" + fileUrl);
URL url = new URL(fileUrl);
//忽略证书
SslUtils.ignoreSsl();
conn = (HttpURLConnection) url.openConnection();
2025-11-12 10:09:03 +00:00
conn.setRequestMethod("GET");
conn.setConnectTimeout(25 * 1000);
conn.setReadTimeout(25 * 1000);
2025-11-12 10:09:03 +00:00
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setInstanceFollowRedirects(false);
inputStream = conn.getInputStream();
logger.info("inputStream -- size:" + inputStream.available());
System.out.println("inputStream:" + inputStream);
2025-11-12 10:09:03 +00:00
// inputStream = getInputStreamFromURL(fileUrl);
attachItem.put("size", getFileSizeByUrl(fileUrl));
2025-11-12 10:09:03 +00:00
// 苍穹自带
TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
tempUrl = cache.saveAsFullUrl((String) attachItem.get("name"), inputStream, 600);
logger.info("tempUrl -- inputStream -- size:" + CacheFactory.getCommonCacheFactory().getTempFileCache().getInputStream(tempUrl).available());
System.out.println(":tempUrl" + tempUrl);
2025-11-12 10:09:03 +00:00
} catch (Exception e) {
logger.info("附件上传失败,堆栈信息:", e);
result.put("isSuccess", "false");
result.put("msg", "转文件流异常" + e);
return result;
2025-11-12 10:09:03 +00:00
} finally {
try {
if (inputStream != null) {
2025-11-12 10:09:03 +00:00
inputStream.close();
}
} catch (Exception e) {
logger.info("附件上传失败,堆栈信息01:", e);
result.put("isSuccess", "false");
result.put("msg", "文件流关闭异常:" + e);
2025-11-12 10:09:03 +00:00
conn.disconnect();
return result;
}
conn.disconnect();
}
try {
attachItem.put("lastModified", System.currentTimeMillis());
2025-11-12 10:09:03 +00:00
MainEntityType dataEntityType = MetadataServiceHelper.getDataEntityType(entity);
String appId = dataEntityType.getAppId();
//上传到临时文件服务器
String actUrl = AttachmentServiceHelper.saveTempToFileService(tempUrl, appId, entity, pk, (String) attachItem.get("name"));
logger.info("actUrl:" + actUrl);
System.out.println("actUrl:" + actUrl);
2025-11-12 10:09:03 +00:00
TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
InputStream in = cache.getInputStream(tempUrl);
FileService service = FileServiceFactory.getAttachmentFileService();
RequestContext requestContext = RequestContext.get();
String uuid = UUID.randomUUID().toString().replace("-", "");
String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
requestContext.getAccountId(), uuid, fileName);
System.out.println("pathParam" + pathParam);
2025-11-12 10:09:03 +00:00
FileItem fileItem = new FileItem(fileName, pathParam, in);
//从临时上传至 文件服务器
String downUrl = service.upload(fileItem);
logger.info("downUrl:" + downUrl);
System.out.println("downUrl:" + downUrl);
2025-11-12 10:09:03 +00:00
attachItem.put("url", actUrl);
attachments.add(attachItem);
// 绑定单据
2025-11-12 10:09:03 +00:00
AttachmentServiceHelper.upload(entity, pk, attachKey, attachments);
} catch (Exception e1) {
logger.info("附件上传失败,堆栈信息e1:", e1);
result.put("isSuccess", "false");
result.put("msg", "上传服务器异常:" + e1);
return result;
2025-11-12 10:09:03 +00:00
}
result.put("isSuccess", "true");
result.put("msg", "附件上传成功");
return result;
}
public static String ioPost(String tempUrl, String fileName, String entity, String size, String attachKey, Object pk) {
2025-11-12 10:09:03 +00:00
List<Map<String, Object>> attachments = new ArrayList<>();
Map<String, Object> attachItem = new HashMap<>();
try {
2025-11-12 10:09:03 +00:00
MainEntityType dataEntityType = MetadataServiceHelper.getDataEntityType(entity);
String appId = dataEntityType.getAppId();
//上传到临时文件服务器
System.out.println(tempUrl);
String actUrl = AttachmentServiceHelper.saveTempToFileService(tempUrl, appId, entity, pk, fileName);
System.out.println("actUrl:" + actUrl);
2025-11-12 10:09:03 +00:00
TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
InputStream in = cache.getInputStream(tempUrl);
FileService service = FileServiceFactory.getAttachmentFileService();
RequestContext requestContext = RequestContext.get();
String uuid = UUID.randomUUID().toString().replace("-", "");
String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
requestContext.getAccountId(), uuid, fileName);
System.out.println("pathParam:" + pathParam);
2025-11-12 10:09:03 +00:00
FileItem fileItem = new FileItem(fileName, pathParam, in);
//从临时上传至 文件服务器
String downUrl = service.upload(fileItem);
System.out.println("downUrl:" + downUrl);
2025-11-12 10:09:03 +00:00
attachItem.put("name", fileName);
attachItem.put("size", size);
attachItem.put("lastModified", System.currentTimeMillis());
2025-11-12 10:09:03 +00:00
attachItem.put("url", actUrl);
attachments.add(attachItem);
// 绑定单据
2025-11-12 10:09:03 +00:00
AttachmentServiceHelper.upload(entity, pk, attachKey, attachments);
} catch (Exception e) {
2025-11-12 10:09:03 +00:00
System.out.println(e);
return e.toString();
}
return "ss";
}
/**
* 根据地址获得数据的字节流并转换成大小
*
2025-11-12 10:09:03 +00:00
* @param strUrl 网络连接地址
* @return
*/
public static int getFileSizeByUrl(String strUrl) {
InputStream inStream = null;
ByteArrayOutputStream outStream = null;
2025-11-12 10:09:03 +00:00
int size = 0;
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
2025-11-12 10:09:03 +00:00
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
inStream = conn.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
2025-11-12 10:09:03 +00:00
outStream.write(buffer, 0, len);
}
byte[] bt = outStream.toByteArray();
2025-11-12 10:09:03 +00:00
if (null != bt && bt.length > 0) {
2025-11-12 10:09:03 +00:00
DecimalFormat df = new DecimalFormat("#");
size = Integer.parseInt(df.format((double) bt.length));
2025-11-12 10:09:03 +00:00
System.out.println("文件大小=" + size);
} else {
2025-11-12 10:09:03 +00:00
System.out.println("没有从该连接获得内容");
}
inStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inStream != null) {
2025-11-12 10:09:03 +00:00
inStream.close();
}
if (outStream != null) {
2025-11-12 10:09:03 +00:00
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return size;
}
private static InputStream getInputStreamFromURL(String urlString) throws IOException {
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
2025-11-12 10:09:03 +00:00
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
2025-11-12 10:09:03 +00:00
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
return conn.getInputStream();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
/**
* 处理url里的中文
*
2025-11-12 10:09:03 +00:00
* @param url
* @return
*/
private static String zhPattern = "[\\u4e00-\\u9fa5]";
/**
* 替换字符串卷
*
* @param str 被替换的字符串
2025-11-12 10:09:03 +00:00
* @param charset 字符集
* @return 替换好的
* @throws UnsupportedEncodingException 不支持的字符集
*/
public static String encode(String str, String charset) throws UnsupportedEncodingException {
Pattern p = Pattern.compile(zhPattern);
Matcher m = p.matcher(str);
StringBuffer b = new StringBuffer();
while (m.find()) {
m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
}
m.appendTail(b);
return b.toString();
}
public static void downloadFile(String fileUrl, String saveDir) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileUrl = URLDecoder.decode(fileUrl);//前面中文encode了这里decode才能保持原文件名
2025-11-12 10:09:03 +00:00
fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
}
InputStream inputStream = connection.getInputStream();
File saveFile = new File(saveDir);
if (!saveFile.exists()) {
2025-11-12 10:09:03 +00:00
saveFile.mkdirs();
}
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println(saveDir + "文件下载完成");
2025-11-12 10:09:03 +00:00
} else {
System.out.println("文件下载失败,错误码:" + responseCode + ";错误文件为" + saveDir);
2025-11-12 10:09:03 +00:00
}
connection.disconnect();
}
}