java base64转文件

/**
     * 把base64转化为文件.
     *
     * @param base64   base64
     * @param filePath 目标文件路径
     * @return boolean isTrue
     */
    public static Boolean decryptByBase64(String base64, String filePath) {

        if (Strings.isNullOrEmpty(base64) && Strings.isNullOrEmpty(filePath)) {
            return Boolean.FALSE;
        }
        try {
            Files.write(Paths.get(filePath),
                    Base64.decodeBase64(base64.substring(base64.indexOf(",") + 1)), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Boolean.TRUE;
    }

    /**
     * 把文件转化为base64.
     *
     * @param filePath 源文件路径
     * @return String 转化后的base64
     */
    public static String encryptToBase64(String filePath) {
        if (!Strings.isNullOrEmpty(filePath)) {
            try {
                byte[] bytes = Files.readAllBytes(Paths.get(filePath));
                return Base64.encodeBase64String(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

代码解释

Files.write(Paths.get(filePath),Base64.decodeBase64(base64.substring(base64.indexOf(",") + 1)), StandardOpenOption.CREATE);

这段代码中 base64.substring(base64.indexOf(",") + 1) 是截取前台传递过来的base64中带的文件标识

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGYWGDEjJR0o......

base64.substring(base64.indexOf(",") + 1) 执行后

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGYWGDEjJR0o......

同样java 中 Base64.encodeBase64String(bytes) 执行结束后 base64 不携带文件标识

转载 https://www.jianshu.com/p/2becba13d9cf

相关文章
相关标签/搜索
精选天下彩票与你同行