java实现文件和base64互转

java实现文件和base64互转

maven依赖version由springboot提供

 <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>

文件转base64

public String  fileToBase64(String file) {
        String ext = file.substring(file.lastIndexOf(".") + 1);

        byte[] data = null;
        // 读取图片字节数组
        try {
        	//file代表文件的网络路径,若为本地文件,可直接创建new file(file)对象
            URL url = new URL(file);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            byte[] buffer = new byte[1024*1000];
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            int len;
            while ((len = in.read(buffer)) != -1) {
                outStream.write(buffer,0,len);
            }
            data=outStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码,得到Base64编码的字符串
        String base64Str = Base64.encodeBase64String(data);
        base64Str = "data:image/" + ext + ";base64," + base64Str;
        return base64Str;
    }

base64转文件


    public String base64ToFile(String base64) {
        File file = null;
        //基础文件夹
        String dateStr = "bbb";
       
        String basedir = localFilePath + "/" + dateStr;
        String sqlUrl = "";
        File dir = new File(basedir);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }

        String[] split = base64.split(",");
        //获取文件的后缀
         String suffix =split  .split("/")[1];
         //剔除文件信息例如(data:image/png;base64)
        base64 = split[split.length-1];
        String fileName = "www-" + System.currentTimeMillis() + "." + suffix;
         byte[] bytes = Base64.decodeBase64(base64);

        //文件输出流
        FileOutputStream fos = null;
        
       
        try {
          
            file = new File(basedir + "/" + fileName);
            fos = new FileOutputStream(file);
            fos.write(bytes);
            //url(虚拟路径)
            sqlUrl = "/aaa/" + dateStr + "/" + fileName;
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return sqlUrl;
    }

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值