gpt4 book ai didi

java - 使用进度回调将文件或 InputStream 上传到 S3

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:57:55 24 4
gpt4 key购买 nike

我们正在使用 Amazon AWS Java 库上传文件,但无法获取上传进度。我们目前正在调用以下内容:

File file = new File(localAsset.getVideoFilePath());
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, localAsset.getFileName(), file);
s3.putObject(putObjectRequest);

我们如何设置回调来检查文件上传进度?

谢谢

最佳答案

我遇到了这个确切的问题并编写了一个简单的 InputStream 包装器来打印出漂亮的进度条:

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

import org.apache.commons.vfs.FileContent;
import org.apache.commons.vfs.FileSystemException;

public class ProgressInputStream extends InputStream {
private final long size;
private long progress, lastUpdate = 0;
private final InputStream inputStream;
private final String name;
private boolean closed = false;

public ProgressInputStream(String name, InputStream inputStream, long size) {
this.size = size;
this.inputStream = inputStream;
this.name = name;
}

public ProgressInputStream(String name, FileContent content)
throws FileSystemException {
this.size = content.getSize();
this.name = name;
this.inputStream = content.getInputStream();
}

@Override
public void close() throws IOException {
super.close();
if (closed) throw new IOException("already closed");
closed = true;
}

@Override
public int read() throws IOException {
int count = inputStream.read();
if (count > 0)
progress += count;
lastUpdate = maybeUpdateDisplay(name, progress, lastUpdate, size);
return count;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int count = inputStream.read(b, off, len);
if (count > 0)
progress += count;
lastUpdate = maybeUpdateDisplay(name, progress, lastUpdate, size);
return count;
}

static long maybeUpdateDisplay(String name, long progress, long lastUpdate, long size) {
if (Config.isInUnitTests()) return lastUpdate;
if (size < B_IN_MB/10) return lastUpdate;
if (progress - lastUpdate > 1024 * 10) {
lastUpdate = progress;
int hashes = (int) (((double)progress / (double)size) * 40);
if (hashes > 40) hashes = 40;
String bar = StringUtils.repeat("#",
hashes);
bar = StringUtils.rightPad(bar, 40);
System.out.format("%s [%s] %.2fMB/%.2fMB\r",
name, bar, progress / B_IN_MB, size / B_IN_MB);
System.out.flush();
}
return lastUpdate;
}
}

(这是从实时代码复制粘贴而来的,因此您可能需要进行一些修正才能使其在您自己的代码中运行。)

然后,只需使用 InputStream 方式放置东西(确保指定大小!),它会为您制作一个漂亮的进度条。如果您想要一个适当的回调,那也很容易做到。

关于java - 使用进度回调将文件或 InputStream 上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3739626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com