我正在尝试将文件上传到 Amazon S3,没什么特别的。我已经设法进行实际上传,并且文件上传成功。剩下的唯一问题是如何取消或中止 putobject 请求
问问题
1455 次
2 回答
1
我遇到了同样的问题,最终使用FileInputStream
而不是File
forPutRequest
并强制关闭流以取消上传。
这会取消 put 请求,因为它无法重试,因为它缺少对文件的引用。
InputStream inputStream = new FileInputStream(file);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(file.length());
PutObjectRequest request = new PutObjectRequest(bucket, key, inputStream, metadata);
取消上传
inputStream.close();
ClientProtocolException
不幸的是,这用堆栈跟踪填充了 logcat 。
于 2014-01-09T04:07:45.240 回答
0
要取消上传,请看看这个,我也在做同样的事情,它工作正常。
public static void main(String[] args) throws Exception {
String clientRegion = "*** Client region ***";
String bucketName = "*** Bucket name ***";
String keyName = "*** Object key ***";
String filePath = "*** Path to file to upload ***";
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new ProfileCredentialsProvider())
.build();
TransferManager tm = TransferManagerBuilder.standard()
.withS3Client(s3Client)
.build();
PutObjectRequest request = new PutObjectRequest(bucketName, keyName, new File(filePath));
// To receive notifications when bytes are transferred, add a
// ProgressListener to your request.
request.setGeneralProgressListener(new ProgressListener() {
public void progressChanged(ProgressEvent progressEvent) {
System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
}
});
// TransferManager processes all transfers asynchronously,
// so this call returns immediately.
Upload upload = tm.upload(request);
// Optionally, you can wait for the upload to finish before continuing.
upload.waitForCompletion();
}
catch(AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
}
catch(SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
参考:https ://docs.aws.amazon.com/AmazonS3/latest/dev/HLTrackProgressMPUJava.html
取消上传在后台线程上使用下面的代码
transferManager.shutdownNow();
于 2019-05-21T15:24:24.127 回答