• 文件与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;
        }

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

    就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
  • 相关阅读:
    IOS:个人笔记|UI_UITableView的优化
    IOS:个人笔记|UI_UITableView
    java基础知识记录(2)
    斐波那契数列
    字符串中数字排序,给定一个字符串“12 33 31 42 ”,或者键盘输入,进行排序
    java基础知识记录(1)
    【Unity】实验二 游戏场景搭建
    Error:java: Compilation failed: internal java compiler error 解决
    Github + Picgo + Typora 让笔记远走高飞
    remote: Incorrect username or password ( access token ) fatal: Authentication failed for
  • 原文地址:https://www.cnblogs.com/zys2019/p/15675074.html
Copyright © 2020-2023  润新知