我想将文件上传到S3,然后在上传成功时将其删除。我正在使用TransferUtility
for(final File p:photos){
String key = getKey(p.getName());
TransferObserver observer = getTransferUtility().upload(S3_BUCKET,key,p);
observer.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if(TransferState.COMPLETED == state){
p.delete();
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
}
@Override
public void onError(int id, Exception ex) {
}
});
}
由于上传是异步的,因此对onStateChanged
的调用必然与for循环异步。那么如何确保每次都删除正确的文件?
更新
可行的一种方法是,如果我可以从observer
内抓取正确的onStateChanged
。然后我就可以了
@Override
public void onStateChanged(int id, TransferState state) {
if(TransferState.COMPLETED == state){
Observer obs = getParentObserver();//similar to a Fragment's getActivity() or getContext()
File file = new File(obs.getAbsoluteFilePath());
file.delete();
}
}
请注意,以下内容无效,因为id
可能永远不会匹配
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
if (observer.getId() == id) {
String filePath = observer.getAbsoluteFilePath();
File file = new File(observer.getAbsoluteFilePath());
}
}
}
答案 0 :(得分:1)
您可以按ID检索转移。
String path = getTransferUtility().getTransferById(id).getAbsoluteFilePath();
new File(path).delete();
getTransferUtility().delete(id);