通过oss地址获取文件的 byte[]

该代码段定义了一个方法downLoadFile,用于从指定的URL下载文件。它首先创建URL对象并打开连接,然后检查HTTP响应码。如果文件不存在,返回null;否则,将文件内容读入字节数组并返回。
byte[] bytes = OSSUtil.downLoadFile(creditImportVO.getFile());
  /**
     * 获取网络文件(不存在为NULL)
     *
     * @param filePath 文件URL
     * @return 文件流
     * @throws Exception
     */
    public static byte[] downLoadFile(String filePath) throws Exception {
        byte[] bytes;
        URL url = new URL(filePath);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
        int httpResult = httpConnection.getResponseCode();
        if (HttpURLConnection.HTTP_NOT_FOUND == httpResult) {
            log.error("OSS服务器文件不存在!");
            return null;
        }
        if (httpResult != HttpURLConnection.HTTP_OK) {
            log.error("从OSS服务器读取文件失败!");
            throw new Exception("从OSS服务器读取文件失败!");
        } else {
            urlConnection.getInputStream();
            InputStream inputStream = urlConnection.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            int ch;
            while ((ch = inputStream.read()) != -1) {
                swapStream.write(ch);
            }
            bytes = swapStream.toByteArray();
        }
        return bytes;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值