HttpClient 上传base64文件

HttpClient发送POST请求,上传MultipartFile文件

1. httpClient 代码

public static String uploadFile2Obj(ObjStoDTO objStoDTO, MultipartFile multipartFile, String imageName, String containerName) {
        JSONObject req = new JSONObject();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(objStoDTO.getIp() + objStoDTO.getContextUrl() + objStoDTO.getObjectUpload());
        log.info("请求的url:" + objStoDTO.getIp() + objStoDTO.getContextUrl() + objStoDTO.getObjectUpload());

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(350000).setConnectionRequestTimeout(350000).setSocketTimeout(600000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-type", "application/octet-stream");
        httpPost.setHeader("objectVO", req.toString());
        log.info("------上传容器的请求头参数:" + req.toString());

        CloseableHttpResponse httpResponse = null;
        InputStream is = null;
        String result = null;
        try
        {
            is = multipartFile.getInputStream();
            InputStreamEntity ise = new InputStreamEntity(is, multipartFile.getSize());
            httpPost.setEntity(ise);
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            log.info("------上传容器的响应结果:" + result);
        } catch (Exception e)
        {
            e.printStackTrace();
            log.error("------文件上传容器失败:", e);
        } finally
        {
            if (httpResponse != null)
            {
                try
                {
                    httpResponse.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            if (httpClient != null)
            {
                try
                {
                    httpClient.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            if (is != null)
            {
                try
                {
                    is.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

2. base64字符串转MultipartFile

public static MultipartFile getMultipartFile(ImageDTO imageDTO) throws IOException {
        String base64 = "data:image/png;base64," + imageDTO.getIMAGEBASE64();
        String[] baseStrs = base64.split(",");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buffer = decoder.decodeBuffer(baseStrs[1]);
        for (int i = 0; i < buffer.length; ++i)
        {
            if (buffer[i] < 0)
            {
                buffer[i] += 256;
            }
        }
        return new Base64MultipartFileUtil(buffer, baseStrs[0], imageDTO.getIMAGENAME());
    }

    public static MultipartFile getObjMultipartFile(ObjImageDTO objImageDTO) throws IOException {
        String base64 = objImageDTO.getImageBase64();
        String[] baseStrs = base64.split(",");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buffer = decoder.decodeBuffer(baseStrs[1]);
        for (int i = 0; i < buffer.length; ++i)
        {
            if (buffer[i] < 0)
            {
                buffer[i] += 256;
            }
        }
        return new Base64MultipartFileUtil(buffer, baseStrs[0], objImageDTO.getObjectName());
    }


public class Base64MultipartFileUtil implements MultipartFile {

    private final byte[] imgContent;
    private final String header;
    private final String fileName;

    public Base64MultipartFileUtil(byte[] imgContent, String header, String fileName) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
        this.fileName = fileName + "." + getFormatName(imgContent);
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

    /**
     * 获取图片类型
     * @param buf
     * @return
     */
    public static String getFormatName(byte[] buf)  {
        InputStream imageStream = new ByteArrayInputStream(buf);
        ImageInputStream imageInputStream = null;
        try
        {
            imageInputStream = ImageIO.createImageInputStream(imageStream);
            Iterator<ImageReader> imageReaderList = ImageIO.getImageReaders(imageInputStream);
            if (imageReaderList.hasNext())
            {
                ImageReader reader = imageReaderList.next();
                return reader.getFormatName();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (imageInputStream != null)
                {
                    imageInputStream.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值