• ssm调用webservice接口并进行文件传输


    ssm调用接口时大致分为三步,

    1,Java后台使用 MultipartFile 接收文件后将类型转为 file ,

    2,将file进行base64加密

    3,调用接口进行传输

    ssm调用webservice代码:

    import org.apache.commons.fileupload.disk.DiskFileItem;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;

    import com.alibaba.fastjson.JSONObject;

    /** * 插入数据测试接口 * @param request * @param fileONE * @param fileTOW * @return */ @RequestMapping("/webJKInsert") @ResponseBody public Map<String,Object> webJKInsert(HttpServletRequest request, MultipartFile fileONE, MultipartFile fileTOW) throws IOException { File fileO = null; File fileT = null; String base64FileO = ""; String base64FileT = ""; String fileONEName = ""; String fileTOWName = ""; if(fileONE!=null?fileONE.getSize()>0:false){//将文件转base64字符串 fileONEName = fileONE.getOriginalFilename();//获取文件名 CommonsMultipartFile cf= (CommonsMultipartFile)fileONE; //File为MultipartFile类型 DiskFileItem fi = (DiskFileItem)cf.getFileItem(); fileO = fi.getStoreLocation(); base64FileO = MulFileUtil.fileBase64(fileO); } if(fileTOW!=null?fileTOW.getSize()>0:false){ fileTOWName = fileTOW.getOriginalFilename();//获取文件名 CommonsMultipartFile cf= (CommonsMultipartFile)fileTOW; //File为MultipartFile类型 DiskFileItem fi = (DiskFileItem)cf.getFileItem(); fileT = fi.getStoreLocation(); base64FileT = MulFileUtil.fileBase64(fileT); } //拼接原文件名和转码后的内容 String fileONES=null; String fileTOWS=null; if(fileONEName!=null && !"".equals(fileONEName) && base64FileO!=null &&!"".equals(base64FileO)){ fileONES = fileONEName+","+base64FileO;//拼接报告1 } if(fileTOWName!=null && !"".equals(fileTOWName) && base64FileT!=null &&!"".equals(base64FileT)){ fileTOWS = fileTOWName+","+base64FileT;//拼接报告2 } String insertXML = InsertXML.insertNotice( fileONES, fileTOWS ); logger.info("调用服务端新增接口中···"); String insert = jk.getInsert(insertXML);//webservice接口 if(insert!=null ?true:false){ logger.info("调用服务端成功···"+insert); }else{ logger.info("调用服务端失败···"+insert); } Map<String,Object> map = JSONObject.parseObject(insert); return map; }

    文件转换工具类

    package com.ljs.utils;
    
    import java.io.*;
    import java.util.Base64;
    
    /**
     * 文件转换工具类
     */
    public class MulFileUtil {
    
        /**
         * file转换为base64
         * @param file
         * @return
         * @throws IOException
         */
        public static String fileBase64(File file) throws IOException {
            String base64 = null;
            InputStream in = null;
            try {
                in = new FileInputStream(file);
                byte[] bytes=new byte[(int)file.length()];
                in.read(bytes);
                base64 = Base64.getEncoder().encodeToString(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return base64;
        }
    
        /**
         * base64转file并写入磁盘
         * @param str
         * @param fileName
         * @return
         * @throws UnsupportedEncodingException
         */
        public static File base64File(String str,String fileName) throws UnsupportedEncodingException {
            File file = null;
            //创建文件目录
            String filePath="/webJKFile";
            File  dir=new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
            }
            BufferedOutputStream bos = null;
            java.io.FileOutputStream fos = null;
            try {
                byte[] bytes = Base64.getDecoder().decode(str);
                file=new File(filePath+"\"+fileName);
                fos = new java.io.FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return file;
        }
    }

    插入数据拼接xml格式报文

    package com.ljs.utils;
    
    /**
     * 插入数据xml
     */
    public class InsertXML {
        public static String insertNotice(String assessment,String research){
    
            String xml="";
            StringBuilder builder = new StringBuilder();
    
            builder.append("<?xml version="1.0" encoding="UTF-8"?>");
            builder.append("<xml-body>");
            builder.append("<Head>");
            builder.append("<Version>1.0</Version>");
            builder.append("<MethodCode>1</MethodCode>");
            builder.append("<BeanId>testService</BeanId>");
            builder.append("<ParamType>xml</ParamType>");
            builder.append("</Head>");
            builder.append("<Body>");
            builder.append("<sysPass>chtrans2000</sysPass>");
            builder.append("<prop>");
    //<!--上传PDF附件必填 -->
            builder.append("<assessment>"+assessment+"</assessment>");
    
            //VARCHAR2(30)<!--上传附件必填 -->
            builder.append("<research>"+research+"</research>");
    
    
            builder.append("</prop>");
            builder.append("</Body>");
            builder.append("</xml-body>");
    
            xml = builder.toString();
            return xml;
        }
    }

    webservice服务端

      /**
       * 数据新增
       * @param xml
       * @return
       */
      public String getInsert(String xml){
        System.out.println("客户端正在调用新增方法......");
        
        Map<String,Object> map = new HashMap<>();
        String name = "";
        String reg = "\d+(\.\d+)?";
        Document doc = null;
        try {
          //连接数据库
          System.out.println("正在连接数据库···");
        Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection
    = DriverManager.getConnection("jdbc:mysql://localhost:3306/jk?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true", "root", "root"); PreparedStatement preparedStatement; doc = DocumentHelper.parseText(xml); // 将字符串转为XML Element rootElt = doc.getRootElement(); // 获取根节 Iterator iterss = rootElt.elementIterator("Body"); ///获取根节点下的子节点body // 遍历body节点 while (iterss.hasNext()) { Element recordEless = (Element) iterss.next(); String sysPass = recordEless.elementTextTrim("sysPass"); // 拿到body节点下的子节点sysPass值 Iterator itersElIterator = recordEless.elementIterator("prop"); // 获取子节点body下的子节点prop // 遍历prop节点下的Response节点 while (itersElIterator.hasNext()) { Element itemEle = (Element) itersElIterator.next(); //map.put("projectName",itemEle.elementTextTrim("projectName")); // 拿到body下的子节点prop下的字节点projectName的值 SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//获取系统时间 //报告1上传 if(itemEle.elementTextTrim("assessment")!=null && !"".equals(itemEle.elementTextTrim("assessment")) && !"null".equals(itemEle.elementTextTrim("assessment"))){ System.out.println("正在上传报告1···"+itemEle.elementTextTrim("assessment")); String uuid = UUID.randomUUID().toString();//生成文件唯一编号 String[] split = itemEle.elementTextTrim("assessment").split(",");//分割获取文件名和经过base64转码后的字符串 String assessmentName = split[0];//文件名 String assessmentFile = split[1];//转码后的字符串 Map<String,Object> maps = MulFileUtil.base64File(assessmentFile,assessmentName);//获取存入file表的字段数据 try { preparedStatement = connection.prepareStatement("insert into file (batch_no,name,address,suffix,createtime) values (?,?,?,?,?)"); preparedStatement.setString(1, uuid); preparedStatement.setString(2, (String) maps.get("jcoriginFileName")); preparedStatement.setString(3,(String) maps.get("fileAddress")); preparedStatement.setString(4,""); preparedStatement.setString(5,simpleDate.format(new Date())); preparedStatement.executeUpdate(); }catch (Exception e){ e.printStackTrace(); name = "{"msg":"false","message":"报告1上传失败"}"; return name; } map.put("assessment",uuid);//报告1 } //报告2上传 if(itemEle.elementTextTrim("research")!=null && !"".equals(itemEle.elementTextTrim("research"))&& !"null".equals(itemEle.elementTextTrim("research"))){ System.out.println("正在上传报告2···"+itemEle.elementTextTrim("research")); String uuid = UUID.randomUUID().toString();//生成文件唯一编号 String[] split = itemEle.elementTextTrim("research").split(",");//分割获取文件名和经过base64转码后的字符串 System.out.println(itemEle.elementTextTrim("research")); String researchName = split[0];//文件名 String researchFile = split[1];//转码后的字符串 Map<String,Object> maps = MulFileUtil.base64File(researchFile,researchName);//获取存入file表的字段数据 try { preparedStatement = connection.prepareStatement("insert into file (batch_no,name,address,suffix,createtime) values (?,?,?,?,?)"); preparedStatement.setString(1, uuid); preparedStatement.setString(2, (String) maps.get("jcoriginFileName")); preparedStatement.setString(3,(String) maps.get("fileAddress")); preparedStatement.setString(4,""); preparedStatement.setString(5,simpleDate.format(new Date())); preparedStatement.executeUpdate(); }catch (Exception e){ name = "{"msg":"false","message":"报告2上传失败"}"; return name; } map.put("research",uuid);//报告2 } //编写SQL,共计34个字段,不包含自增长id,isdelete,createtime三个。 preparedStatement = connection.prepareStatement("insert into notice (createtime,assessment,research) VALUES (?,?,?)"); //占位符,从1开始 preparedStatement.setString(1, simpleDate.format(new Date())); preparedStatement.setString(2, (String) map.get("assessment")); preparedStatement.setString(3, (String) map.get("research")); //返回的结果是一个整数表示该操作影响了数据表中的几条数据 int i = preparedStatement.executeUpdate(); if(i>0){ name = "{"msg":"true","message":"新增成功"}"; System.out.println("客户端调用成功"); }else{ name = "{"msg":"false","message":"新增失败"}"; System.out.println("客户端调用失败"); } //关闭 preparedStatement.close(); connection.close(); System.out.println("调用新增方法成功,已关闭数据库连接···"); } } } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return name; }
  • 相关阅读:
    T-SQL逻辑查询的各阶段
    linqtosql(GroupBy/Having/Count/Sum/Min/Max/Avg操作符)
    jquery获取select下拉框的值以及change时间绑定
    英汉翻译功能的简单实现
    jQuery zTree默认加载一级几点
    Linq第一篇
    vs2015+win10搭开发环境
    asp.net mvc 中使用静态页
    .net中的异步操作
    (转载)TFS2013安装+配置
  • 原文地址:https://www.cnblogs.com/ljmm/p/13362029.html
Copyright © 2020-2023  润新知