请求工具类和base64转成MultipartFile工具类

请求工具类 hutool包HttpRequest带请求头和请求体发送post请求

将MultipartFile文件保存到本地

package org.jeecg.modules.quota.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.ZOSUtil;
import org.jeecg.modules.quota.controller.DataSynchronismController;
import org.jeecg.modules.quota.entity.SysCertPdf;
import org.jeecg.modules.quota.service.ISysCertPdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author leitao
 * @Date 2023/9/21 15:28
 * @description: 请求工具类
 * @Title: RequestYxeUtil
 * @Package org.jeecg.modules.quota.utils
 */
public class RequestYxeUtil {
    //    private static final String token_url = "http://23:89/xxxx/xxxx/token?clientId=2c9642bd21c0000&clientSecret=6abc4457bc60e0d2e0b08a8b9828c6e9d86250458b4de51bf82d9604abeb987d3";
    //token(线上)
    private static final String token_url = "http://23:89/xxxx/xxxx/token?clientId=2c9fb2d21c0000&clientSecret=6ab3e8291b9af828c6e9d86250458b4de51bf82d9604abeb987d3";
    //获取渔船照片证据
    private static final String XeblCertificate_url = "http://23:89/xxx/xxxx/xxxxx/XeblCertificate";

    //token()
    private static final String XeblCyzp_token_url = "http://28:87/xxx//xxxx/token";

    //获取船员照片
    private static final String XeblCyzp_url = "http://28:87/xxx//xxxx/CyService/getCyPhoto";

    /**
     * 限额xxxx证书
     *
     * @param cm
     * @param ycid
     * @throws IOException
     */
    public static ArrayList<SysCertPdf> xeblCertificate(String cm, String ycid, String uploadType) throws Exception {
        ArrayList<SysCertPdf> sysCertPdfs = new ArrayList<>();
        String requestResult = HttpRequest.post(token_url).execute().body();
        JSONObject jsonResult = JSONUtil.parseObj(requestResult);
        String code = jsonResult.getStr("code");
        if ("0".equals(code)) {
            String result = jsonResult.getStr("result");
            JSONObject resultJson = JSONUtil.parseObj(result);
            String accessToken = resultJson.getStr("accessToken");

            //json格式
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("shipName", cm);
            paramMap.put("shipInfoId", ycid);
            String xeblCertificateResult = HttpRequest.post(XeblCertificate_url)
                    .header("X-Access-Token", accessToken)
                    .body(JSONUtil.toJsonPrettyStr(paramMap)).execute().body();
            JSONObject jsonObject = JSONUtil.parseObj(xeblCertificateResult);
            String code1 = jsonObject.getStr("code");
            if ("200".equals(code1)) {
                //将result转成JSONObject
                JSONObject json_result = jsonObject.getJSONObject("result");
                Map<String, Object> map = JSONUtil.parseObj(json_result);

                Map<String, SysCertPdf> sysCertPdfMap = new HashMap<>();

                Object pngCert = map.get("pngCert");
                if (pngCert instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) pngCert;
                    for (Object o : jsonArray) {
                        Map<String, Object> pngCertMap = (Map<String, Object>) o;
                        for (String value : pngCertMap.keySet()) {
                            SysCertPdf sysCertPdf = new SysCertPdf();
                            String base64 = (String) pngCertMap.get(value);
                            MultipartFile pngMultipartFile = Base64ToMultipartFileConverter.convert(base64, ycid + ".png");
                            uploadFile(pngMultipartFile, value, "png", ycid, uploadType, sysCertPdf);
                            sysCertPdfMap.put(value, sysCertPdf);
                        }
                    }
                }
                Object pdfCert = map.get("pdfCert");
                if (pdfCert instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) pdfCert;
                    for (Object o : jsonArray) {
                        Map<String, Object> pngCertMap = (Map<String, Object>) o;
                        for (String value : pngCertMap.keySet()) {
                            String base64 = (String) pngCertMap.get(value);
                            MultipartFile pdfMultipartFile = Base64ToMultipartFileConverter.convert(base64, ycid + ".pdf");
                            uploadFile(pdfMultipartFile, value, "pdf", ycid, uploadType, sysCertPdfMap.get(value));
                        }
                    }
                }
                for (String s : sysCertPdfMap.keySet()) {
                    sysCertPdfs.add(sysCertPdfMap.get(s));
                }
            }

        }
        return sysCertPdfs;
    }

    /**
     * 将文件上传到服务器
     *
     * @param multipartFile
     * @param value
     * @param type
     * @param ycid
     * @param uploadType
     * @param sysCertPdf
     * @return
     * @throws Exception
     */
    public static SysCertPdf uploadFile(MultipartFile multipartFile, String value, String type, String ycid, String uploadType, SysCertPdf sysCertPdf) throws Exception {
        String bizPath = "pdfCert" + "/" + value;
        String fileUrl = " ";
        if ("png".equals(type)) {
            if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
                fileUrl = MinioUtil.upload(multipartFile, bizPath);
                fileUrl = fileUrl.substring(1, fileUrl.length());
                //保存文件信息
                // 获取文件名
                sysCertPdf.setModelName(value);
                sysCertPdf.setPngPath(fileUrl);
                sysCertPdf.setCertId(ycid);
                sysCertPdf.setCertType(1);
                sysCertPdf.setDeleted(0);
                return sysCertPdf;
            } else if (CommonConstant.UPLOAD_TYPE_ZOS.equals(uploadType)) {
                fileUrl = ZOSUtil.upload(multipartFile, bizPath);
                sysCertPdf.setModelName(value);
                sysCertPdf.setPngPath(fileUrl);
                sysCertPdf.setCertId(ycid);
                sysCertPdf.setCertType(1);
                sysCertPdf.setDeleted(0);
                return sysCertPdf;
            }
        } else if ("pdf".equals(type)) {
            if (BeanUtil.isNotEmpty(sysCertPdf)) {
                if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
                    fileUrl = MinioUtil.upload(multipartFile, bizPath);
                    //保存文件信息
                    // 获取文件名
                    sysCertPdf.setPdfPath(fileUrl);
                    return sysCertPdf;
                } else if (CommonConstant.UPLOAD_TYPE_ZOS.equals(uploadType)) {
                    fileUrl = ZOSUtil.upload(multipartFile, bizPath);
                    sysCertPdf.setPdfPath(fileUrl);
                    return sysCertPdf;
                }
            }
        }

        return null;
    }

    /**
     * 将文件保存到本地
     *
     * @param file
     * @param type
     * @param value
     * @param ycid
     * @throws IOException
     */
    public static void saveFileToLocal(MultipartFile file, String type, String value, String ycid) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = "E:\\workspace\\" + fileName + "." + type;
        String filePath1 = "E:\\workspace\\" + "pdfCert" + "/" + value + "/" + ycid + "." + type;
        File localFile = new File(filePath1);
        // 文件名
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();// 新建目录
        }
        file.transferTo(localFile);
    }

    /**
     * 根据船只身份证查询照片
     *
     * @param sfzhm
     * @param uploadType
     * @return
     */
    public static SysCertPdf xeblCyzp(String sfzhm, String uploadType) throws Exception {
        //
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("clientId", "402881f167e00001");
        paramMap.put("clientSecret", "482978cf5bcb08bc51dcec5b680ccff5ff54ceef53cfde562");
        //form-data
        String requestResult = HttpRequest.post(XeblCyzp_token_url).form(paramMap)
                .execute().body();
        JSONObject jsonResult = JSONUtil.parseObj(requestResult);

        String code = jsonResult.getStr("code");
        if ("0".equals(code)) {
            String result = jsonResult.getStr("result");
            JSONObject resultJson = JSONUtil.parseObj(result);
            String accessToken = resultJson.getStr("accessToken");
            String[] str = new String[]{sfzhm};
            String xeblCyzpUrlResult = HttpRequest.post(XeblCyzp_url)
                    .header("X-Access-Token", accessToken)
                    .body(Arrays.toString(str)).execute().body();
            JSONObject jsonObject = JSONUtil.parseObj(xeblCyzpUrlResult);
            String code1 = jsonObject.getStr("code");
            if ("200".equals(code1)) {
                String str_result = jsonObject.getStr("result");
                Map<String, String> collect = Arrays.stream(str_result.split(",")).collect(Collectors.toMap((e -> e.split(":")[0]), (e -> e.split(":")[1])));
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder append = stringBuilder.append("[{\"").append(sfzhm).append("\"");
                String sfzhmBase64 = collect.get(append.toString());
                String substring = sfzhmBase64.substring(1,sfzhmBase64.length()-3);
                MultipartFile jpgMultipartFile = Base64ToMultipartFileConverter.convert(substring, sfzhm + ".jpg");
                return uploadCyPhoto(jpgMultipartFile, sfzhm, uploadType);
            }
        }

        return null;
    }

    /**
     * 上传船员照片
     * @param jpgMultipartFile
     * @param sfzhm
     * @param uploadType
     * @return
     * @throws Exception
     */
    private static SysCertPdf uploadCyPhoto(MultipartFile jpgMultipartFile, String sfzhm, String uploadType) throws Exception {
        String bizPath = "cyPhoto";
        String fileUrl = " ";
        SysCertPdf sysCertPdf = new SysCertPdf();
        if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
            fileUrl = MinioUtil.upload(jpgMultipartFile, bizPath);
            fileUrl = fileUrl.substring(1);
            //保存文件信息
            // 获取文件名
            sysCertPdf.setModelName("cyPhoto");
            sysCertPdf.setPngPath(fileUrl);
            sysCertPdf.setCertId(sfzhm);
            sysCertPdf.setCertType(2);
            sysCertPdf.setDeleted(0);
            return sysCertPdf;
        }else if (CommonConstant.UPLOAD_TYPE_ZOS.equals(uploadType)) {
            fileUrl = ZOSUtil.upload(jpgMultipartFile, bizPath);
            sysCertPdf.setModelName("cyPhoto");
            sysCertPdf.setPngPath(fileUrl);
            sysCertPdf.setCertId(sfzhm);
            sysCertPdf.setCertType(2);
            sysCertPdf.setDeleted(0);
            return sysCertPdf;
        }
        return null;
    }
}

将 base64转成MultipartFile 

package org.jeecg.modules.quota.utils;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.Base64Utils;  
import org.springframework.core.io.ByteArrayResource;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64ToMultipartFileConverter {

    public static MultipartFile convert(String base64String, String fileName) {
        // 解码Base64字符串为字节数组
        byte[] bytes = Base64.getDecoder().decode(base64String);

        // 创建MockMultipartFile对象并设置文件内容和文件名
        MockMultipartFile multipartFile = new MockMultipartFile("file", fileName, "application/octet-stream", bytes);

        return multipartFile;
    }

}

hutool发送+参数get请求

//地址
        String checkur = downloa.getLoadConfigUrl();
        //设备序列号
        String deviceId = downloa.getDeviceId();

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("deviceId", deviceId);
        //!!!!!!!!!!!!!!++++=
        //发送post请求
        String jsonResult = HttpRequest.post(checkur)
                .body(JSONUtil.toJsonPrettyStr(paramMap))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(jsonResult);

        String responseCode = jsonObject.getStr("responseCode");
        if (Constants.SUCCESS.equals(responseCode)) {
            BasicDownloadRes basicDownloadRes = new BasicDownloadRes();
            basicDownloadRes.setResponseMessage(jsonObject.getStr("responseMessage"));
            basicDownloadRes.setResponseCode(responseCode);
            this.insertBasicDownloadRes(basicDownloadRes);
            /**
             * @Description: TODO
             * @Author LeiTao
             * @Date 2022/4/23
             * @Version V1.0
             **/
            String data = jsonObject.getStr("data");

            Map map = JSONUtil.parseObj(data);
            //行政区划代码
            List<Map<String,Object>> region = (List<Map<String,Object>>) map.get("region");
            this.basicDataDownloadRegionService.deleteRegionAll();

            for (Map<String,Object> regionMap : region) {
                BasicDataDownloadRegion basicDataDownloadRegionService = new BasicDataDownloadRegion();
                basicDataDownloadRegionService.setCode((String) regionMap.get("code"));
                basicDataDownloadRegionService.setFullName((String) regionMap.get("fullName"));
                basicDataDownloadRegionService.setName((String) regionMap.get("name"));
                basicDataDownloadRegionService.setType((Integer) regionMap.get("type"));
                this.basicDataDownloadRegionService.insertBasicDataDownloadRegion(basicDataDownloadRegionService);
            }

            //行业代码
            List<Map<String,Object>> industry = (List<Map<String,Object>>) map.get("industry");
            basicDataDownloadIndustryService.deleteIndustryAll();

            for (Map<String, Object> industryMap : industry) {
                BasicDataDownloadIndustry basicDataDownloadIndustry = new BasicDataDownloadIndustry();
                basicDataDownloadIndustry.setCode((String) industryMap.get("code"));
                basicDataDownloadIndustry.setFullName((String) industryMap.get("fullName"));
                basicDataDownloadIndustry.setJgzh(Boolean.toString((Boolean) industryMap.get("jgzh")));
                basicDataDownloadIndustry.setName((String) industryMap.get("name"));
                basicDataDownloadIndustry.setPcode((String) industryMap.get("pcode"));
                basicDataDownloadIndustryService.insertBasicDataDownloadIndustry(basicDataDownloadIndustry);
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用JavaBase64类和Spring的MultipartFile类来实现Base64MultipartFile工具类。下面是一个示例代码: ```java import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.Base64; public class Base64ToMultipartFileUtil { public static MultipartFile base64ToMultipartFile(String base64) throws IOException { // 解码Base64字符串 byte[] decodedBytes = Base64.getDecoder().decode(base64); // 创建临时文件 String tempFileName = "temp.jpg"; // 可以根据需要修改文件名和类型 File tempFile = new File(tempFileName); FileUtils.writeByteArrayToFile(tempFile, decodedBytes); // 创建MultipartFile对象 MultipartFile multipartFile = new MockMultipartFile(tempFile.getName(), tempFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), new FileInputStream(tempFile)); // 删除临时文件 tempFile.delete(); return multipartFile; } } ``` 这个工具类base64ToMultipartFile方法接受一个Base64字符串作为输入,并返回对应的MultipartFile对象。它首先将Base64字符串解码为字节数组,然后将字节数组写入临时文件中。接着使用MockMultipartFile类创建MultipartFile对象,并指定文件名、原始文件名和文件类型。最后,删除临时文件并返回MultipartFile对象。 请注意,这里使用的是Spring的MockMultipartFile类,它是用于测试的模拟实现。在实际应用中,你需要根据自己的需求选择合适的MultipartFile实现类。 希望这个工具类对你有帮助!如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值