将InputStream转化为Base64,将Base64转化为InputStream

最近项目上遇到文件上传转化的问题,还有本地文件上传转化Base64,做个记录。

Base64转化为InputStream

import org.apache.commons.codec.binary.Base64;
public static InputStream baseToInputStream(final byte[] base64byte){
    ByteArrayInputStream bs= null;
    try {
        byte[] bytes = Base64.decodeBase64(base64byte);
        bs = new ByteArrayInputStream(bytes);
    } catch (Exception e) {
        logger.error("文件处理异常",e);
    }
    return bs;
}
InputStream转化为Base64
public static String getBase64FromInputStream(InputStream in) {

    byte[] data = null;

    try {
        ByteArrayOutputStream bs= new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = in.read(buff, 0, 100)) > 0) {
            bs.write(buff, 0, rc);
        }
        data = bs.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return new String(Base64.encodeBase64(data));
}

猜你喜欢

转载自blog.csdn.net/airyearth/article/details/107815403