要获取Springboot上传文件到Minio的进度,可以使用以下步骤:

  1. 创建自定义的 ProgressInputStream 类,该类继承 FilterInputStream 类,并覆盖 read 方法来跟踪输入流的读取进度。示例代码如下:
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ProgressInputStream extends FilterInputStream {
    private long bytesRead = 0;
    private long contentLength;

    public ProgressInputStream(InputStream in, long contentLength) {
        super(in);
        this.contentLength = contentLength;
    }

    @Override
    public int read() throws IOException {
        int b = in.read();
        if (b != -1) {
            bytesRead++;
        }
        return b;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int bytesRead = in.read(b, off, len);
        if (bytesRead > 0) {
            this.bytesRead += bytesRead;
        }
        return bytesRead;
    }

    public long getContentLength() {
        return contentLength;
    }

    public long getBytesRead() {
        return bytesRead;
    }
}
  1. 在上传文件的方法中,使用 ProgressInputStream 包装 InputStream,并将其传递给Minio的 putObject 方法中。然后,使用 ProgressEvent 类的 progress() 方法来获取上传进度。示例代码如下:
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.PutObjectResponse;
import io.minio.errors.MinioException;
import org.springframework.web.multipart.MultipartFile;

public class MinioService {
    private final MinioClient minioClient;

    public MinioService(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    public PutObjectResponse uploadFile(String bucketName, String objectName, MultipartFile file) throws IOException, MinioException {
        ProgressInputStream progressInputStream = new ProgressInputStream(file.getInputStream(), file.getSize());

        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(progressInputStream, progressInputStream.getContentLength(), -1)
                .build();

        ProgressListener progressListener = new ProgressListener() {
            @Override
            public void progressChanged(ProgressEvent progressEvent) {
                System.out.println("Uploaded " + progressInputStream.getBytesRead() + " bytes of " + progressInputStream.getContentLength() + " bytes");
            }
        };

        progressInputStream.addProgressListener(progressListener);

        return minioClient.putObject(args);
    }
}

这样,每次上传文件时,都会打印上传进度信息。您可以根据需要将其改为记录到日志文件或其他位置。

Springboot获取minio821上传文件进度

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

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