调用方返回文件流,获取文件流 inputstream 并转换为MultipartFile 或一般文件输出流下载,案例 inputstream 转 byte[]

一、获取到文件流并下载该文件流,当作普通文件

处理文件流并保存为文件的例子:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileStreamDownloader {

    public static void downloadFileStream(String urlString, String saveFilePath) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try {
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 创建文件输出流用于保存文件
                try (InputStream in = connection.getInputStream();
                     FileOutputStream out = new FileOutputStream(saveFilePath)) {
                    
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    System.out.println("File downloaded successfully.");
                }
            } else {
                throw new Exception("GET request failed with response code: " + responseCode);
            }
        } finally {
            connection.disconnect();
        }
    }

    public static void main(String[] args) {
        try {
            String urlString = "http://example.com/file/to/download";
            String savePath = "local/file/path/to/save/downloaded.file";
            downloadFileStream(urlString, savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这段代码做了以下修改:

  1. 方法签名和返回类型更改为处理文件下载,不再返回JSONObject
  2. 添加了一个参数saveFilePath来指定保存文件的本地路径。
  3. 使用FileOutputStream代替BufferedReader来处理输入流,这更适合处理二进制文件(如图片、文档等)。
  4. 读取输入流并直接写入到输出流中,直到没有更多字节可读。
  5. 删除了原本用于构建JSON响应的代码块,因为现在处理的是文件流而不是文本数据。

请确保替换urlString变量的值为目标文件的URL地址,以及savePath变量为你希望在本地保存文件的路径及文件名。

二、将获取的文件流转为 MultipartFile

要将从HTTP GET请求获得的文件流转换为MultipartFile对象,你首先需要了解MultipartFile通常用于处理HTTP请求中的文件上传部分,而并非直接用于处理HTTP响应中的文件流。不过,你可以创建一个自定义的类或方法来模拟MultipartFile的行为,以便在后续操作中使用它,比如通过Spring框架的文件处理机制进行处理。

以下是一个简化的示例,展示如何将获取的输入流包装成一个模拟的MultipartFile对象。请注意,这个例子仅作为概念上的演示,并未直接实现MultipartFile接口的所有细节,但在很多场景下可能已经足够使用。

首先,你需要一个辅助类来模拟MultipartFile的行为:

import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;

import java.io.ByteArrayResource;
import java.io.IOException;
import java.io.InputStream;

public class FileStreamToMultipartFile {

    /**
     * 将InputStream转换为MockMultipartFile,以便模拟MultipartFile行为。
     *
     * @param inputStream 文件流
     * @param fileName 文件名
     * @return MockMultipartFile对象
     * @throws IOException 如果读取输入流时发生错误
     */
    public static MultipartFile convertInputStreamToMultipartFile(InputStream inputStream, String fileName) throws IOException {
        byte[] byteArray = inputStream.readAllBytes();
        return new MockMultipartFile(fileName, fileName, "application/octet-stream", byteArray);
    }
}

然后,在你的下载方法中使用这个辅助类将文件流转换为MultipartFile

import org.springframework.mock.web.MockMultipartFile;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileStreamDownloader {

    public static MockMultipartFile downloadAsStreamAndConvertToFile(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try {
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取文件流并转换为MultipartFile
                try (InputStream inputStream = connection.getInputStream()) {
                    String[] pathParts = urlString.split("/");
                    String fileName = pathParts[pathParts.length - 1]; // 简单示例:从URL中提取文件名,请根据实际情况调整
                    return FileStreamToMultipartFile.convertInputStreamToMultipartFile(inputStream, fileName);
                }
            } else {
                throw new Exception("GET request failed with response code: " + responseCode);
            }
        } finally {
            connection.disconnect();
        }
    }

    public static void main(String[] args) {
        try {
            String urlString = "http://example.com/file/to/download";
            MockMultipartFile multipartFile = downloadAsStreamAndConvertToFile(urlString);
            // 现在你可以像处理真正的MultipartFile一样处理multipartFile
            System.out.println("File downloaded and converted to MultipartFile with name: " + multipartFile.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请注意,这个方案利用了Spring框架提供的MockMultipartFile类来模拟一个MultipartFile实例,这在单元测试或者某些特定的处理流程中非常有用。然而,如果你的应用程序不需要直接与Spring的文件上传功能集成,直接处理原始的输入流并将其保存到文件系统或其他存储服务上可能更为直接有效。

注意:
byte[] byteArray = inputStream.readAllBytes();

readAllBytes 方法可能依赖某一个jdk 版本,可以使用如下方式替代,将inputstream 转为 byte[]
InputStream转换为byte[]数组的一个现代且简洁的方法是使用ByteArrayOutputStream,结合try-with-resources语句来自动管理资源。这里是一个示例代码片段:

import java.io.*;

public class InputStreamToByteArray {

    public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            return outputStream.toByteArray();
        }
    }

    public static void main(String[] args) {
        // 示例用法
        try (InputStream inputStream = new FileInputStream("path/to/your/file")) {
            byte[] byteArray = inputStreamToByteArray(inputStream);
            // 现在 byteArray 包含了文件的全部内容
            System.out.println("File converted to byte array successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这段代码首先创建了一个ByteArrayOutputStream实例,并在一个try-with-resources块中使用它,确保即使发生异常也能正确关闭输出流。然后,它读取InputStream的内容到缓冲区,并将缓冲区的内容写入ByteArrayOutputStream,直到没有更多的字节可以读取(即read()返回-1)。最后,通过调用toByteArray()方法将输出流的内容转换为byte[]数组。

请注意,你需要根据实际情况替换 "path/to/your/file" 为实际文件路径,并处理好可能抛出的IOException

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将一个`InputStream`对象转换成`MultipartFile`对象,可以按照以下步骤进行操作: 1. 创建一个`ByteArrayOutputStream`对象,将`InputStream`中的数据写入到该对象中。 2. 创建一个`CommonsMultipartFile`对象,将`ByteArrayOutputStream`中的数据作为构造函数的参数传入。 3. 设置`CommonsMultipartFile`对象的文件名和文件类型等信息。 下面是一个Java代码示例: ```java import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItem; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamToMultipartFileConverter { public static MultipartFile convert(InputStream inputStream, String fileName, String contentType) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] bytes = outputStream.toByteArray(); FileItem fileItem = new DiskFileItem("file", contentType, false, fileName, bytes.length , null); fileItem.getOutputStream().write(bytes); return new CommonsMultipartFile(fileItem); } } ``` 使用时,可以调用`convert()`法将`InputStream`对象转换成`MultipartFile`对象,示例如下: ```java InputStream inputStream = new FileInputStream("test.txt"); MultipartFile multipartFile = InputStreamToMultipartFileConverter.convert(inputStream, "test.txt", "text/plain"); ``` 这样就将`InputStream`转换成了`MultipartFile`对象。注意,这里使用了`CommonsMultipartFile`,因此需要在Maven中引入`commons-fileupload`和`commons-io`依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值