1. 首先需要获取要上传的图片文件的路径。
  2. 使用FileInputStream读取文件内容,将读取到的内容写入ByteArrayOutputStream中。
  3. 获取ByteArrayOutputStream中的字节数组,即图片的二进制数据。
  4. 使用字节缓冲输入输出流(BufferedInputStream和BufferedOutputStream)将二进制数据上传到目标项目中。
  5. 关闭输入输出流,释放资源。

示例代码:

import java.io.*;

public class UploadImage {
    public static void main(String[] args) {
        String filePath = "C:\\image.jpg"; // 要上传的图片文件路径

        try {
            // 读取文件内容
            FileInputStream fis = new FileInputStream(filePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            fis.close();
            baos.close();

            // 获取图片的二进制数据
            byte[] imageData = baos.toByteArray();

            // 上传图片到目标项目
            String targetFilePath = "D:\\project\\image.jpg"; // 目标项目中保存图片的路径
            BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(imageData));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFilePath));
            byte[] targetBuffer = new byte[1024];
            int targetLen;
            while ((targetLen = bis.read(targetBuffer)) != -1) {
                bos.write(targetBuffer, 0, targetLen);
            }
            bis.close();
            bos.close();
            
            System.out.println("图片上传成功!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
``
1【需求】:上传图片到当前项目中使用字节缓冲输入输出流

原文地址: https://www.cveoy.top/t/topic/fqYR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录