复制对象

复制对象

您可以使用 copyObject 接口复制对象,您需要设置复制的对象名,所在的桶以及目标桶和对象名:

public void copyObject() throws AmazonClientException {
	String oriBucket = bucket;
	String destBucket = bucket;
	String oriKey = "ExampleObject.txt";
	String destKey = "ExampleObject1.txt";
	ObjectMetadata metadataCopy = new ObjectMetadata();
	metadataCopy.setContentType("text/json");
	CopyObjectRequest request = new CopyObjectRequest(oriBucket, oriKey, destBucket, destKey);
	s3Client.copyObject(request);
	System.out.println("changeMetadataViaCopyObject success");
}

大文件分片复制

文件比较大(超过1GB)的情况下,直接使用copyObject 可能会出现超时,需要使用分片复制的方式进行文件复制,TransferManager封装了分片复制的接口,可以用于复制文件。

public void copy() {
	try {
		String oriBucket = bucket;
		String destBucket = bucket;
		String oriKey = "1.avi";
		String destKey = "2.avi";

		// TransferManager 只需要初始化一次,可以用于多个上传任务
		TransferManager transMgr = TransferManagerBuilder.standard()
				.withS3Client(s3Client)
				.withMinimumUploadPartSize(10*1024*1024L)
				.withMultipartUploadThreshold(100*1024*1024L)
				.build();

		// TransferManager 采用异步方式进行处理,因此该调用会立即返回。
		CopyObjectRequest request = new CopyObjectRequest(oriBucket, oriKey, destBucket, destKey);
		Copy copy = transMgr.copy(request);
		CopyResult result = copy.waitForCopyResult();
		System.out.println("copy success, etag=" + result.getETag());
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

修改对象元数据

媒体存储没有直接修改对象元数据的方法,上传文件之后就不能修改了,可以使用 copyObject 接口修改对象元数据,注意:源bucket和目的bucket一致,源key和目的key一致。

public void changeMetadataViaCopyObject() throws AmazonClientException {
	String oriKey = "ExampleObject.txt";
	String destKey = oriKey;        // 复制到原来的key
	ObjectMetadata metadataCopy = new ObjectMetadata();
	metadataCopy.setContentType("text/json");
	CopyObjectRequest request = new CopyObjectRequest(bucket, oriKey, bucket, destKey)
			.withNewObjectMetadata(metadataCopy);
	s3Client.copyObject(request);
	System.out.println("changeMetadataViaCopyObject success");
}