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

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;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个开源的 Java Web 框架,能够快速创建基于 Spring 的应用程序。OSS(Object Storage Service)是阿里云提供的对象存储服务,可以用来存储和管理各种类型的非结构化数据(图片、视频等)。 Spring Boot 集成了阿里云 OSS SDK,通过调用 SDK 中的 API 可以实现文件的上传和下载。具体步骤如下: 1. 添加阿里云 OSS SDK 依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.9.0</version> </dependency> ``` 2. 在 application.yml 文件中配置阿里云 OSS 的 accessKeyId、accessKeySecret、endpoint、bucket 等信息: ```yaml spring: aliyun: oss: access-key-id: your-accessKeyId access-key-secret: your-accessKeySecret endpoint: your-endpoint bucket-name: your-bucketName ``` 3. 在代码中使用 OSSClient 对象实现文件下载: ```java @Autowired private OSSClient ossClient; public void downloadFile(String objectName, HttpServletResponse response) throws IOException { OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); byte[] bytes = IOUtils.toByteArray(inputStream); response.getOutputStream().write(bytes); } ``` 其中,objectName 表示需要下载的文件名,response 表示 HTTP 响应对象。该方法会从 OSS获取指定文件的输入流,将输入流转换为字节数组,然后写入到 HTTP 响应对象的输出流中,从而实现文件的下载。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值