From 2333ad00c0d1e1eb63ed845af4c7ea6a66c1b12b Mon Sep 17 00:00:00 2001 From: sez Date: Fri, 5 Dec 2025 10:55:48 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9D=9E=E9=87=87=E8=B4=AD=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E9=99=84=E4=BB=B6=E7=94=A8base64=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=B5=81=E6=8E=A5=E6=94=B6=E5=B9=B6=E7=94=9F=E6=88=90=E9=99=84?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/controller/SupplierControl.java | 19 +- lc123/cloud/app/api/model/SupplierModel.java | 14 +- .../app/api/utils/AttachmentFileUtil.java | 238 +++++++++++++----- 3 files changed, 188 insertions(+), 83 deletions(-) diff --git a/lc123/cloud/app/api/controller/SupplierControl.java b/lc123/cloud/app/api/controller/SupplierControl.java index 2e96fe4..3a759ec 100644 --- a/lc123/cloud/app/api/controller/SupplierControl.java +++ b/lc123/cloud/app/api/controller/SupplierControl.java @@ -170,9 +170,9 @@ public class SupplierControl implements Serializable { rowMsg.add("供应商附件名称为空"); billStatus = false; } - String attachmentUrl = attachmentBean.getAttachmentUrl(); - if (StringUtils.isEmpty(attachmentUrl)) { - rowMsg.add("供应商附件地址为空"); + String fileString = attachmentBean.getFileString(); + if (StringUtils.isEmpty(fileString)) { + rowMsg.add("供应商附件文件流"); billStatus = false; } @@ -201,7 +201,7 @@ public class SupplierControl implements Serializable { bd_supplier.set("tqq9_basedatafield1", tqq9_basedatafield1); bd_supplier.set("creator", creator); bd_supplier.set("createtime", createtime); - bd_supplier.set("tqq9_textfield33", societycreditcode); + bd_supplier.set("societycreditcode", societycreditcode); bd_supplier.set("tqq9_usagescenarios", tqq9_usagescenarios); bd_supplier.set("tqq9_datefield5_clrq", tqq9_datefield5_clrq); bd_supplier.set("tqq9_textfield210", tqq9_textfield210); @@ -307,17 +307,18 @@ public class SupplierControl implements Serializable { SupplierModel.DataBean.AttachmentBean attachmentBean = attachment.get(j); String attachementname = attachmentBean.getAttachmentName(); - BigDecimal attachementsize = BigDecimal.ZERO; - String attachementurl = attachmentBean.getAttachmentUrl(); +// BigDecimal attachementsize = BigDecimal.ZERO; + String fileString = attachmentBean.getFileString(); +// String attachementurl = attachmentBean.getAttachmentUrl(); /*DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("tqq9_registration", new QFilter[]{new QFilter("number", QCP.equals, "1134256")}); List> attachments = AttachmentServiceHelper.getAttachments("tqq9_registration", dynamicObject.getPkValue(), "tqq9_attachmentpanelsh"); Object url = attachments.get(0).get("url"); - attachementurl= (String) url;*/ - String uid1 = uid.toString() + index++; + attachementurl= (String) url; + String uid1 = uid.toString() + index++;*/ Map uploadres = null; try { - uploadres = AttachmentFileUtil.saveUrlFile2Attchment(uid1, entityName, bd_supplier.getPkValue(), attachementurl, attachementname, attachementsize.toString(), "tqq9_attachmentpanelap"); + uploadres = AttachmentFileUtil.saveUrlFile2Attchment(entityName, bd_supplier.getPkValue(), attachementname, fileString, "tqq9_attachmentpanelap"); } catch (Exception ee1) { rowMsg.add("第" + (j + 1) + "条附件信息处理错误,上传失败!The No." + j + 1 + " attachment information processing error." + ee1); break; diff --git a/lc123/cloud/app/api/model/SupplierModel.java b/lc123/cloud/app/api/model/SupplierModel.java index 983a2f8..b9ee27c 100644 --- a/lc123/cloud/app/api/model/SupplierModel.java +++ b/lc123/cloud/app/api/model/SupplierModel.java @@ -274,8 +274,8 @@ public class SupplierModel implements Serializable { @ApiParam(value = "附件.附件名称", example = "50Kr3",required = true,position = 1) private String attachmentName; - @ApiParam(value = "附件.附件地址", example = "hsUsx",required = true,position = 2) - private String attachmentUrl; + @ApiParam(value = "附件文件流", example = "hsUsx",required = true,position = 2) + private String fileString; public String getAttachmentName() { return attachmentName; @@ -285,13 +285,15 @@ public class SupplierModel implements Serializable { this.attachmentName = attachmentName; } - public String getAttachmentUrl() { - return attachmentUrl; + public String getFileString() { + return fileString; } - public void setAttachmentUrl(String attachmentUrl) { - this.attachmentUrl = attachmentUrl; + public void setFileString(String fileString) { + this.fileString = fileString; } + + } @ApiModel diff --git a/lc123/cloud/app/api/utils/AttachmentFileUtil.java b/lc123/cloud/app/api/utils/AttachmentFileUtil.java index aae2873..ae0a88a 100644 --- a/lc123/cloud/app/api/utils/AttachmentFileUtil.java +++ b/lc123/cloud/app/api/utils/AttachmentFileUtil.java @@ -12,6 +12,7 @@ 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; import kd.bos.util.FileNameUtils; import java.io.*; @@ -30,16 +31,114 @@ import java.util.regex.Pattern; public class AttachmentFileUtil { private final static Log logger = LogFactory.getLog(AttachmentFileUtil.class); + /** - * @param entity 目标单据实体标识 - * @param pk 目标数据id - * @param fileUrl 待存入文件的url - * @param fileName 带存入文件名称 - * @param fileSize 带存入文件大小 + * 将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 saveUrlFile2Attchment( String entity, Object pk, String fileName, String base64Image, String attachKey) { + Map 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> attachItems = new ArrayList<>(); + Map attachItem = new HashMap<>(); + attachItem.put("name", fileName); + attachItem.put("size", sourceFileSize); + + + 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 带存入文件大小 * @param attachKey 附件面板标识 * @throws IOException */ - public static Map saveUrlFile2Attchment(String uid1,String entity, Object pk, String fileUrl, String fileName,String fileSize, String attachKey){ + public static Map saveUrlFile2Attchment(String uid1, String entity, Object pk, String fileUrl, String fileName, String fileSize, String attachKey) { List> attachments = new ArrayList<>(); Map attachItem = new HashMap<>(); Map result = new HashMap<>(); @@ -52,55 +151,55 @@ public class AttachmentFileUtil { // 连接url并 获取输入流 // fileUrl = URLEncoder.encode(fileUrl,"UTF-8"); // fileUrl = java.net.URLDecoder.decode(fileUrl, "UTF-8"); - fileUrl = encode(fileUrl,"UTF-8"); + fileUrl = encode(fileUrl, "UTF-8"); logger.info("fileUrl:" + fileUrl); URL url = new URL(fileUrl); //忽略证书 SslUtils.ignoreSsl(); - conn = (HttpURLConnection)url.openConnection(); + conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); - conn.setConnectTimeout(25*1000); - conn.setReadTimeout(25*1000); + 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); + logger.info("inputStream -- size:" + inputStream.available()); + System.out.println("inputStream:" + inputStream); // inputStream = getInputStreamFromURL(fileUrl); - attachItem.put("size", getFileSizeByUrl(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); + System.out.println(":tempUrl" + tempUrl); } catch (Exception e) { - logger.info("附件上传失败,堆栈信息:",e); - result.put("isSuccess", "false"); - result.put("msg", "转文件流异常"+e); - return result; + logger.info("附件上传失败,堆栈信息:", e); + result.put("isSuccess", "false"); + result.put("msg", "转文件流异常" + e); + return result; } finally { try { - if(inputStream!=null){ + if (inputStream != null) { inputStream.close(); } } catch (Exception e) { - logger.info("附件上传失败,堆栈信息01:",e); - result.put("isSuccess", "false"); - result.put("msg", "文件流关闭异常:"+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()); + 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); + 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(); @@ -108,41 +207,41 @@ public class AttachmentFileUtil { String uuid = UUID.randomUUID().toString().replace("-", ""); String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), uuid, fileName); - System.out.println("pathParam"+pathParam); + 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); + 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; + } 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){ + public static String ioPost(String tempUrl, String fileName, String entity, String size, String attachKey, Object pk) { List> attachments = new ArrayList<>(); Map attachItem = new HashMap<>(); - try{ + 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); + 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(); @@ -150,22 +249,22 @@ public class AttachmentFileUtil { String uuid = UUID.randomUUID().toString().replace("-", ""); String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(), requestContext.getAccountId(), uuid, fileName); - System.out.println("pathParam:"+pathParam); + System.out.println("pathParam:" + pathParam); FileItem fileItem = new FileItem(fileName, pathParam, in); //从临时上传至 文件服务器 - String downUrl =service.upload(fileItem); - System.out.println("downUrl:"+downUrl); + 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("lastModified", System.currentTimeMillis()); attachItem.put("url", actUrl); attachments.add(attachItem); - // 绑定单据 + // 绑定单据 AttachmentServiceHelper.upload(entity, pk, attachKey, attachments); - }catch (Exception e){ + } catch (Exception e) { System.out.println(e); return e.toString(); } @@ -174,16 +273,17 @@ public class AttachmentFileUtil { /** * 根据地址获得数据的字节流并转换成大小 + * * @param strUrl 网络连接地址 * @return */ - public static int getFileSizeByUrl(String strUrl){ - InputStream inStream=null; - ByteArrayOutputStream outStream=null; + 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(); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); inStream = conn.getInputStream(); @@ -191,29 +291,29 @@ public class AttachmentFileUtil { outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; - while( (len=inStream.read(buffer)) != -1 ){ + while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } - byte[] bt = outStream.toByteArray(); + byte[] bt = outStream.toByteArray(); - if(null != bt && bt.length > 0){ + if (null != bt && bt.length > 0) { DecimalFormat df = new DecimalFormat("#"); - size = Integer.parseInt(df.format((double) bt.length)); + size = Integer.parseInt(df.format((double) bt.length)); System.out.println("文件大小=:" + size); - }else{ + } else { System.out.println("没有从该连接获得内容"); } inStream.close(); outStream.close(); } catch (Exception e) { e.printStackTrace(); - }finally{ - try{ - if(inStream !=null){ + } finally { + try { + if (inStream != null) { inStream.close(); } - if(outStream !=null){ + if (outStream != null) { outStream.close(); } } catch (IOException e) { @@ -227,9 +327,9 @@ public class AttachmentFileUtil { URL url = null; try { url = new URL(urlString); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为3秒 - conn.setConnectTimeout(3*1000); + conn.setConnectTimeout(3 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 @@ -242,6 +342,7 @@ public class AttachmentFileUtil { /** * 处理url里的中文 + * * @param url * @return */ @@ -250,7 +351,7 @@ public class AttachmentFileUtil { /** * 替换字符串卷 * - * @param str 被替换的字符串 + * @param str 被替换的字符串 * @param charset 字符集 * @return 替换好的 * @throws UnsupportedEncodingException 不支持的字符集 @@ -282,13 +383,14 @@ public class AttachmentFileUtil { if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } - } else { fileUrl= URLDecoder.decode(fileUrl);//前面中文encode了,这里decode才能保持原文件名 + } 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()){ + File saveFile = new File(saveDir); + if (!saveFile.exists()) { saveFile.mkdirs(); } String saveFilePath = saveDir + File.separator + fileName; @@ -303,9 +405,9 @@ public class AttachmentFileUtil { outputStream.close(); inputStream.close(); - System.out.println(saveDir+"文件下载完成"); + System.out.println(saveDir + "文件下载完成"); } else { - System.out.println("文件下载失败,错误码:" + responseCode+";错误文件为"+saveDir); + System.out.println("文件下载失败,错误码:" + responseCode + ";错误文件为" + saveDir); } connection.disconnect(); }