文件与base64如何互转?

很多情况下,需要把文件转成base64字符串进行传输,原因就是直接使用流传输可能会导致流接收不完整。使用base64字符串接收然后再转码保存文件可避免这种问题。下面的方法仅供参考:

1.base64转文件

 /**
     * base64转文件保存
     *
     * @param base64 base64字符串
     * @param basePath 文件保存的根路径
     * @param suffix   文件后缀
     * @param fileName 文件名
     * @return
     */
    public static String[] base64ToFile(String base64, String basePath, String suffix, String fileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        if (basePath.contains("\\")) {
            basePath = basePath.replace("\\", File.separator);
        }
        File f = createDir(basePath + File.separator + dateStr);
        if (null == fileName) {
            //补齐后缀
            suffix = suffix.trim();
            if (!suffix.startsWith(".") && suffix.indexOf(".") == -1) {
                suffix = "." + suffix;
            }
            fileName = UUID.randomUUID() + suffix;
        }
        try {
            byte[] buffer = new BASE64Decoder().decodeBuffer(base64);
            File file = new File(f, fileName);
            FileOutputStream out = new FileOutputStream(file);
            out.write(buffer);
            out.close();
            String[] path = {dateStr, fileName};
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

根据传入的base64字符串,可根据传入的文件后缀和UUID作为文件名把文件保存到指定位置,也可以直接传入文件名进行保存;最终都返回文件的路径和文件名。

2.文件转base64

   /**
     * 文件转base64
     *
     * @param filePath
     * @return
     */
    public static String fileToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

通过传入文件的路径对文件进行转换。

posted @ 2021-12-17 20:28  钟小嘿  阅读(2860)  评论(0编辑  收藏  举报