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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM