我正在尝试将文件上传到Amazon S3,没什么特别的。我已设法进行实际上传,文件上传成功。剩下的唯一问题是如何取消或中止putobject请求
答案 0 :(得分:1)
我遇到了同样的问题,最后使用FileInputStream
代替File
PutRequest
并强制关闭流以取消上传。
这会取消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。
答案 1 :(得分: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();