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

314 lines
12 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.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);
/**
* @param entity 目标单据实体标识
* @param pk 目标数据id
* @param fileUrl 待存入文件的url
* @param fileName 带存入文件名称
* @param fileSize 带存入文件大小
* @param attachKey 附件面板标识
* @throws IOException
*/
public static Map<String, Object> saveUrlFile2Attchment(String uid1,String entity, Object pk, String fileUrl, String fileName,String fileSize, String attachKey){
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");
logger.info("fileUrl:" + fileUrl);
URL url = new URL(fileUrl);
//忽略证书
SslUtils.ignoreSsl();
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(25*1000);
conn.setReadTimeout(25*1000);
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);
// inputStream = getInputStreamFromURL(fileUrl);
attachItem.put("size", getFileSizeByUrl(fileUrl));
// 苍穹自带
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);
} catch (Exception e) {
logger.info("附件上传失败,堆栈信息:",e);
result.put("isSuccess", "false");
result.put("msg", "转文件流异常"+e);
return result;
} finally {
try {
if(inputStream!=null){
inputStream.close();
}
} catch (Exception e) {
logger.info("附件上传失败,堆栈信息01:",e);
result.put("isSuccess", "false");
result.put("msg", "文件流关闭异常:"+e);
conn.disconnect();
return result;
}
conn.disconnect();
}
try{
attachItem.put("lastModified",System.currentTimeMillis());
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);
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);
FileItem fileItem = new FileItem(fileName, pathParam, in);
//从临时上传至 文件服务器
String downUrl =service.upload(fileItem);
logger.info("downUrl:"+downUrl);
System.out.println("downUrl:"+downUrl);
attachItem.put("url", actUrl);
attachments.add(attachItem);
// 绑定单据
AttachmentServiceHelper.upload(entity, pk, attachKey, attachments);
}catch(Exception e1){
logger.info("附件上传失败,堆栈信息e1:",e1);
result.put("isSuccess", "false");
result.put("msg", "上传服务器异常:"+e1);
return result;
}
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){
List<Map<String, Object>> attachments = new ArrayList<>();
Map<String, Object> attachItem = new HashMap<>();
try{
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);
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);
FileItem fileItem = new FileItem(fileName, pathParam, in);
//从临时上传至 文件服务器
String downUrl =service.upload(fileItem);
System.out.println("downUrl:"+downUrl);
attachItem.put("name", fileName);
attachItem.put("size", size);
attachItem.put("lastModified",System.currentTimeMillis());
attachItem.put("url", actUrl);
attachments.add(attachItem);
// 绑定单据
AttachmentServiceHelper.upload(entity, pk, attachKey, attachments);
}catch (Exception e){
System.out.println(e);
return e.toString();
}
return "ss";
}
/**
* 根据地址获得数据的字节流并转换成大小
* @param strUrl 网络连接地址
* @return
*/
public static int getFileSizeByUrl(String strUrl){
InputStream inStream=null;
ByteArrayOutputStream outStream=null;
int size = 0;
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
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 ){
outStream.write(buffer, 0, len);
}
byte[] bt = outStream.toByteArray();
if(null != bt && bt.length > 0){
DecimalFormat df = new DecimalFormat("#");
size = Integer.parseInt(df.format((double) bt.length));
System.out.println("文件大小=" + size);
}else{
System.out.println("没有从该连接获得内容");
}
inStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(inStream !=null){
inStream.close();
}
if(outStream !=null){
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();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回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里的中文
* @param url
* @return
*/
private static String zhPattern = "[\\u4e00-\\u9fa5]";
/**
* 替换字符串卷
*
* @param str 被替换的字符串
* @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才能保持原文件名
fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
}
InputStream inputStream = connection.getInputStream();
File saveFile=new File(saveDir);
if(!saveFile.exists()){
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+"文件下载完成");
} else {
System.out.println("文件下载失败,错误码:" + responseCode+";错误文件为"+saveDir);
}
connection.disconnect();
}
}