文件系列三:网络文件与base64字符串的转换

说明

  • 网络文件URL 转 Base64字符串
  • Base64字符串 转 本地文件
  • 根据URL下载网络

示例代码

package com.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件 / base64字符串 转换器
 *
 * @author: hmm
 * @date: 2020/9/16 16:17
 */
public class FileTest {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 通过图片的url获取图片的base64字符串
     *
     * @param fileUrl 文件网络url
     * @return 图片base64的字符串
     */
    public static String fileToBase64(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.info("[fileToBase64] fileUrl参数为空");
            return "";
        }
        // 反斜杠"\" 转 正斜杠 "/"
        fileUrl = fileUrl.replaceAll("\\\\", "/");
//        imgUrl = URLEncoder.encode(imgUrl,"UTF-8");
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            url = new URL(fileUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                //连接失败/链接失效/文件不存在
                log.error("[fileToBase64] 连接失败/链接失效/文件不存在 ");
                return "";
            }
            // 得到输入流
            is = httpURLConnection.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }

            if (is != null) {
                is.close();
            }
            if (outStream != null) {
                outStream.close();
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

            log.info("[fileToBase64] 文件转base64字符串成功");
            // 对字节数组Base64编码
            return new BASE64Encoder().encode(outStream.toByteArray());
        } catch (Exception ex) {
            log.error("[fileToBase64] 文件转base64字符串异常: " + ex.toString());
            ex.printStackTrace();
            return "";
        }
    }
    

    /**
     * base64字符串转文件
     *
     * @param base64 文件base64字符串
     * @param path   文件存储全路径(目录 + 文件名 含后缀)
     * @return
     */
    public static String base64ToFile(String base64, String path) {
        //图像数据为空
        if (StringUtils.isBlank(base64) || StringUtils.isBlank(path)) {
            log.error("[base64ToFile] 参数为空 ");
            return "";
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // 根据path创建文件夹及文件
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                // 创建文件夹
                fileParent.mkdirs();
            }
            // 创建文件
            file.createNewFile();

            //Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 生成指定格式的文件
            out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            log.info("[base64ToFile] base64转文件成功");
            return path;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("[base64ToFile] base64字符串转文件异常: " + ex.toString());
            return "";
        }
    }


    /**
     * 根据URL下载 网络文件
     *
     * @param url  文件地址
     * @param path 文件存储全路径(目录 + 文件名 含后缀)
     * @return 下载后的文件存储路径
     */
    public static String downloadHttpFile(String url, String path) {
        try {
            // URL urlPath = new URL(url);
            // 下载文件中文名处理
            URL urlPath = new URL(UriUtils.encodePath(url, "UTF-8"));
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                // 创建文件夹
                fileParent.mkdirs();
            }
            // 创建文件
            file.createNewFile();
            FileUtils.copyURLToFile(urlPath, new File(path));
            log.info("[downloadHttpFile] 根据URL下载文件成功");
            return "";
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error("[downloadHttpFile] 根据URL下载文件异常: " + ex.toString());
            return "";
        }

    }


    /**
     * 从网络Url中下载文件
     *
     * @param url  文件地址
     * @param path 文件存储目录+ 文件名 含后缀
     */
    public static void downLoadFile(String url, String path) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        HttpURLConnection conn = null;
        ByteArrayOutputStream byteOutputStream = null;
        try {
            URL urlPath = new URL(url);
            conn = (HttpURLConnection) urlPath.openConnection();

            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            byteOutputStream = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                byteOutputStream.write(buffer, 0, len);
            }

            //文件保存位置
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                // 创建文件夹
                fileParent.mkdirs();
            }
            // 创建文件
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            outputStream.write(byteOutputStream.toByteArray());

            if (outputStream != null) {
                outputStream.close();
            }
            if (byteOutputStream != null) {
                byteOutputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error("[downLoadFile]  从网络Url中下载文件 异常" + ex.toString());
        }

    }


    public static void main(String[] args) {
        String imageUrl = "http://10.2.0.1:8083/image/nj.jpg";
        String base64 = fileToBase64(imageUrl);
        System.out.println(base64);
        base64ToFile(base64, "D:\\image\\test.jpg");

        downloadHttpFile(imageUrl, "D:\\image\\test2.jpg");


        String pdfUrl = "http://10.2.0.1:8083/image/test.pdf";
        String base642 = fileToBase64(pdfUrl);
        System.out.println(base642);
        base64ToFile(base642, "D:\\image\\11.pdf");

        downLoadFile(pdfUrl, "D:\\image\\22.pdf");

    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值