E签宝合同模板之图片控件填充

在合同模板上添加了图片控件并且设置了相关高级服务属性参数名后,要填充该控件。分三步:

参考官方文档:上传本地文件

第一步:获取上传文件地址:"{{url}}/v1/files/getUploadUrl",本实例上传的图片是网络地址,因此步骤如下:

public static GetFileUploadUrlDto getFileUploadAddress(String imgPath){
		//请求接口
		String url = "/v1/files/getUploadUrl";

		//参数封装 参数
		Map<String, Object> mapResult = new LinkedHashMap<String, Object>();
		String contentMd5 = FileUtil.getStringContentMD5(imgPath);
		System.out.println("contentMd5:"+contentMd5);
		mapResult.put("contentMd5",contentMd5);
		mapResult.put("contentType","application/octet-stream");
		mapResult.put("fileName",imgPath.substring(imgPath.lastIndexOf("/")+1)+".jpeg");
		mapResult.put("fileSize",FileUtil.getImageSize(imgPath));
		mapResult.put("convert2Pdf",false);
		String paramStr = JsonUtil.objectTojson(mapResult);
		String md5String = null;
		try {
			md5String = Encryption.doContentMD5(paramStr);
		} catch (DefineException e) {
			e.printStackTrace();
		}
		//请求方法
		String HTTPMethod = "POST";
		//封装公共请求参数
		String message = Encryption.appendSignDataString(HTTPMethod, HeaderConstant.ACCEPT.VALUE(), md5String,
				HeaderConstant.CONTENTTYPE_JSON.VALUE(), HeaderConstant.DATE.VALUE(),
				HeaderConstant.HEADERS.VALUE(), url);
		logger.info("获取文件上传地址公共请求参数 message:" + message);


		String result = null;
		String reqUrl = "https://openapi.esign.cn" + url;
		try {
			// 整体做sha256签名
			String reqSignature = Encryption.doSignatureBase64(message, Factory.getProject_scert());
			logger.info("sha256签名:"+reqSignature);
			logger.info("获取文件上传地址参数:"+paramStr);
			logger.info("获取文件上传地址传入的md5:"+md5String);
			result = sendHttpPostJsonUtf(reqUrl, paramStr, md5String, reqSignature,1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result:"+result);
		GetFileUploadUrlDto dto = (GetFileUploadUrlDto) JSONObject.parseObject(result, GetFileUploadUrlDto.class);
		return  dto;
	}

package utils;

import com.xx.util.file.FileUtils;
import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件工具
 * @author zmd
 */
public class FileUtil {
    /**
     * 网络文件URL转换成FileInputStream
     * @param netUrl
     * @return
     */
    public static FileInputStream netUrlToFileFileInputStream(String netUrl){
        FileInputStream fileInputStream = null;
        try {
            URL url = new URL(netUrl);
            HttpURLConnection  connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为HEAD,这样服务器只返回状态码,不会传输内容
            connection.connect();
            InputStream inputStream  = connection.getInputStream();
            fileInputStream = convertToFileInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileInputStream;
    }

    /**
     * inputStream 转换成 FileInputStream
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static FileInputStream convertToFileInputStream(InputStream inputStream) throws IOException {
        File tempFile = File.createTempFile("temp", ".jpeg");
        tempFile.deleteOnExit();

        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return new FileInputStream(tempFile);
    }

    /***
     * 文件上传-计算字符串的Content-MD5
     * @param str 文件路径
     * @return
     */
    public static String getStringContentMD5(String str) {
        // 获取文件MD5的二进制数组(128位)
        byte[] bytes = getFileMD5Bytes1282(str);
        // 对文件MD5的二进制数组进行base64编码
        return new String(Base64.encodeBase64(bytes));
    }
    /***
     * 获取文件MD5-二进制数组(128位)
     *
     * @param filePath
     * @return
     */
    public static byte[] getFileMD5Bytes1282(String filePath) {
        FileInputStream fis = null;
        byte[] md5Bytes = null;
        try {
            File file = new File(filePath);
            fis = FileUtil.netUrlToFileFileInputStream(filePath);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
            fis.close();
        } catch (NoSuchAlgorithmException | IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return md5Bytes;
    }

    /**
     * 获取网络文件大小 kb
     * @param netUrl
     * @return
     */
    public static Long getImageSize(String netUrl){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(netUrl);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为HEAD,这样服务器只返回状态码,不会传输内容
            connection.setRequestMethod("HEAD");
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取图片字节长度,即大小
        assert connection != null;
        return connection.getContentLengthLong();
    }

    /**
     * 网络文件转换成File
     * @param netUrl
     * @return
     */
    public static File getFileByNetUrl(String netUrl){
        File tempFile = null;
        try {
            tempFile = File.createTempFile("temp", ".jpeg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tempFile != null){
            tempFile.deleteOnExit();

            try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                FileInputStream inputStream = netUrlToFileFileInputStream(netUrl);
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(tempFile.getAbsolutePath());
        }
        return tempFile;
    }
}

第二步:获取文件上传流

	/**
	 * 文件流上传
	 * @param uploadUrl 文件上传地址,链接有效期60分钟
	 * @param imgPath 网络文件地址
	 */
	public static GetFileUploadStreamDto uploadFileStream(String uploadUrl,String imgPath){
		//请求头入参
		//与【步骤1 获取文件上传地址】Body体中contentMd5值一致
		String contentMD5 = FileUtil.getStringContentMD5(imgPath);
		//请求参数
//		HTTP BODY:待上传文件的二进制字节流。注意:此文件必须与contentMd5值对应的文件一致
		File file = FileUtil.getFileByNetUrl(imgPath);
		String result = null;
		try {
			logger.info("文件流上传参数:"+file);
			logger.info("获取文件上传地址传入的md5:"+contentMD5);
			result = sendUploadFileHttpPutJsonUtf(uploadUrl, file, contentMD5);
		} catch (Exception e) {
			e.printStackTrace();
		}
		GetFileUploadStreamDto dto = (GetFileUploadStreamDto) JSONObject.parseObject(result, GetFileUploadStreamDto.class);
		return dto;
	}

	/**
	 * 上传文件流执行方法
	 * @param url 文件上传地址
	 * @param file 文件
	 * @param md5
	 * @return
	 * @throws Exception
	 */
	public static String sendUploadFileHttpPutJsonUtf(String url, File file, String md5) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(url);

		httpPut.setHeader("Content-MD5", md5);
		httpPut.setHeader("Content-Type", HeaderConstant.CONTENTTYPE_STREAM.VALUE());

		FileEntity fileEntity = new FileEntity(file);
		StringEntity stringEntity = new StringEntity(EntityUtils.toString(fileEntity), ContentType.APPLICATION_OCTET_STREAM);
		stringEntity.setContentType("multipart/form-data");
		httpPut.setEntity(stringEntity);
		CloseableHttpResponse response = httpClient.execute(httpPut);
		System.err.println(response);
		System.out.println(response.getStatusLine().getStatusCode() + "\n");
		HttpEntity entity = response.getEntity();
		String responseContent = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseContent);
		response.close();
		httpClient.close();
		return responseContent;
	}

第三步,根据图片属性对应的fileId的值,即可在生产合同的时候填充图片

最后注意:上面部分关于Encryption的没有相关代码,可以从官方文档里找到对应的代码。另外此文件是针对图片。注意文件工具类转换文件时候的后缀。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞流银河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值