Java禁止覆蓋同名文件
默認(rèn)情況下,如果新添加文件與現(xiàn)有文件(Object)同名且對(duì)該文件有訪問(wèn)權(quán)限,則新添加的文件將覆蓋原有的文件。本文介紹如何通過(guò)設(shè)置請(qǐng)求頭x-oss-forbid-overwrite在簡(jiǎn)單上傳、拷貝文件及分片上傳等場(chǎng)景中禁止覆蓋同名文件。
注意事項(xiàng)
本文以華東1(杭州)外網(wǎng)Endpoint為例。如果您希望通過(guò)與OSS同地域的其他阿里云產(chǎn)品訪問(wèn)OSS,請(qǐng)使用內(nèi)網(wǎng)Endpoint。關(guān)于OSS支持的Region與Endpoint的對(duì)應(yīng)關(guān)系,請(qǐng)參見(jiàn)OSS訪問(wèn)域名、數(shù)據(jù)中心、開(kāi)放端口。
本文以從環(huán)境變量讀取訪問(wèn)憑證為例。如何配置訪問(wèn)憑證,請(qǐng)參見(jiàn)Java配置訪問(wèn)憑證。
本文以OSS域名新建OSSClient為例。如果您希望通過(guò)自定義域名、STS等方式新建OSSClient,請(qǐng)參見(jiàn)新建OSSClient。
簡(jiǎn)單上傳
以下代碼用于簡(jiǎn)單上傳時(shí)禁止覆蓋同名文件:
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環(huán)境變量中獲取訪問(wèn)憑證。運(yùn)行本代碼示例之前,請(qǐng)確保已設(shè)置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫B(tài)ucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。
String objectName = "exampledir/object";
String content = "Hello OSS!";
// 填寫B(tài)ucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 創(chuàng)建OSSClient實(shí)例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 創(chuàng)建PutObjectRequest對(duì)象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// 指定上傳文件操作時(shí)是否覆蓋同名Object。
// 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object。
// 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。
// 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-forbid-overwrite", "true");
putObjectRequest.setMetadata(metadata);
// 上傳文件。
ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
拷貝文件
通過(guò)CopyObjectRequest拷貝
以下代碼用于通過(guò)CopyObjectRequest拷貝小文件時(shí)禁止覆蓋同名文件:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問(wèn)憑證。運(yùn)行本代碼示例之前,請(qǐng)確保已設(shè)置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫源Bucket名稱。 String sourceBucketName = "srcexamplebucket"; // 填寫源Object的完整路徑,完整路徑中不能包含Bucket名稱。 String sourceObjectName = "srcexampleobject.txt"; // 填寫與源Bucket處于同一地域的目標(biāo)Bucket名稱。 String destinationBucketName = "desexamplebucket"; // 填寫目標(biāo)Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String destinationObjectName = "desexampleobject.txt"; // 填寫Bucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。 String region = "cn-hangzhou"; // 創(chuàng)建OSSClient實(shí)例。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 創(chuàng)建CopyObjectRequest對(duì)象。 CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); // 設(shè)置新的文件元數(shù)據(jù)。 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("text/html"); // 指定拷貝文件操作時(shí)是否覆蓋同名Object。 // 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object // 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。 // 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。 metadata.setHeader("x-oss-forbid-overwrite", "true"); copyObjectRequest.setNewObjectMetadata(metadata); // 拷貝文件。 CopyObjectResult result = ossClient.copyObject(copyObjectRequest); System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
拷貝大文件
以下代碼用于拷貝大文件(分片拷貝)時(shí)禁止覆蓋同名文件:
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 從環(huán)境變量中獲取訪問(wèn)憑證。運(yùn)行本代碼示例之前,請(qǐng)確保已設(shè)置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填寫源Bucket名稱。 String sourceBucketName = "srcexamplebucket"; // 填寫源Object的完整路徑,完整路徑中不能包含Bucket名稱。 String sourceObjectName = "srcexampleobject.txt"; // 填寫與源Bucket處于同一地域的目標(biāo)Bucket名稱。 String destinationBucketName = "desexamplebucket"; // 填寫目標(biāo)Object的完整路徑。Object完整路徑中不能包含Bucket名稱。 String destinationObjectName = "desexampleobject.txt"; // 填寫Bucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。 String region = "cn-hangzhou"; // 創(chuàng)建OSSClient實(shí)例。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName); // 獲取被拷貝文件的大小。 long contentLength = objectMetadata.getContentLength(); // 設(shè)置分片大小為10MB。 long partSize = 1024 * 1024 * 10; // 計(jì)算分片總數(shù)。 int partCount = (int) (contentLength / partSize); if (contentLength % partSize != 0) { partCount++; } System.out.println("total part count:" + partCount); // 初始化拷貝任務(wù)。可以通過(guò)InitiateMultipartUploadRequest指定目標(biāo)文件元數(shù)據(jù)。 InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName); // 指定拷貝文件操作時(shí)是否覆蓋同名Object。 // 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object。 // 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。 // 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。 ObjectMetadata metadata = new ObjectMetadata(); metadata.setHeader("x-oss-forbid-overwrite", "true"); initiateMultipartUploadRequest.setObjectMetadata(metadata); InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest); String uploadId = initiateMultipartUploadResult.getUploadId(); // 分片拷貝。 List<PartETag> partETags = new ArrayList<PartETag>(); for (int i = 0; i < partCount; i++) { // 計(jì)算每個(gè)分片的大小。 long skipBytes = partSize * i; long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes; // 創(chuàng)建UploadPartCopyRequest。可以通過(guò)UploadPartCopyRequest指定限定條件。 UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); uploadPartCopyRequest.setUploadId(uploadId); uploadPartCopyRequest.setPartSize(size); uploadPartCopyRequest.setBeginIndex(skipBytes); uploadPartCopyRequest.setPartNumber(i + 1); UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest); // 將返回的分片ETag保存到partETags中。 partETags.add(uploadPartCopyResult.getPartETag()); } // 完成分片拷貝任務(wù)。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest( destinationBucketName, destinationObjectName, uploadId, partETags); // 指定拷貝文件操作時(shí)是否覆蓋同名Object。 // 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object // 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。 // 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。 completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true"); ossClient.completeMultipartUpload(completeMultipartUploadRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
分片上傳
以下代碼用于分片上傳時(shí)禁止覆蓋同名文件:
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環(huán)境變量中獲取訪問(wèn)憑證。運(yùn)行本代碼示例之前,請(qǐng)確保已設(shè)置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫B(tài)ucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Object的完整路徑。Object完整路徑中不能包含Bucket名稱。
String objectName = "exampledir/object";
// 填寫B(tài)ucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 創(chuàng)建OSSClient實(shí)例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 創(chuàng)建InitiateMultipartUploadRequest對(duì)象。
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
// 指定分片上傳操作時(shí)是否覆蓋同名Object。
// 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object。
// 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。
// 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-forbid-overwrite", "true");
request.setObjectMetadata(metadata);
// 初始化分片。
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
// 返回uploadId,它是分片上傳事件的唯一標(biāo)識(shí),您可以根據(jù)這個(gè)ID來(lái)發(fā)起相關(guān)的操作,如取消分片上傳、查詢分片上傳等。
String uploadId = upresult.getUploadId();
// partETags是PartETag的集合。PartETag由分片的ETag和分片號(hào)組成。
List<PartETag> partETags = new ArrayList<PartETag>();
// 計(jì)算文件有多少個(gè)分片。
final long partSize = 1 * 1024 * 1024L; // 1MB
final File sampleFile = new File("<localFile>");
long fileLength = sampleFile.length();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// 遍歷分片上傳。
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
InputStream instream = new FileInputStream(sampleFile);
// 跳過(guò)已經(jīng)上傳的分片。
instream.skip(startPos);
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(instream);
// 設(shè)置分片大小。除了最后一個(gè)分片沒(méi)有大小限制,其他的分片最小為100KB。
uploadPartRequest.setPartSize(curPartSize);
// 設(shè)置分片號(hào)。每一個(gè)上傳的分片都有一個(gè)分片號(hào),取值范圍是1~10000,如果超出這個(gè)范圍,OSS將返回InvalidArgument的錯(cuò)誤碼。
uploadPartRequest.setPartNumber( i + 1);
// 每個(gè)分片不需要按順序上傳,甚至可以在不同客戶端上傳,OSS會(huì)按照分片號(hào)排序組成完整的文件。
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// 每次上傳分片之后,OSS的返回結(jié)果會(huì)包含一個(gè)PartETag。PartETag將被保存到partETags中。
partETags.add(uploadPartResult.getPartETag());
}
// 創(chuàng)建CompleteMultipartUploadRequest對(duì)象。
// 完成分片上傳操作時(shí),需要提供所有有效的partETags。OSS收到提交的partETags后,會(huì)逐一驗(yàn)證每個(gè)分片的有效性。當(dāng)所有的數(shù)據(jù)分片驗(yàn)證通過(guò)后,OSS將把這些分片組合成一個(gè)完整的文件。
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// 指定分片上傳操作時(shí)是否覆蓋同名Object。
// 不指定x-oss-forbid-overwrite時(shí),默認(rèn)覆蓋同名Object。
// 指定x-oss-forbid-overwrite為false時(shí),表示允許覆蓋同名Object。
// 指定x-oss-forbid-overwrite為true時(shí),表示禁止覆蓋同名Object,如果同名Object已存在,程序?qū)?bào)錯(cuò)。
completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true");
// 完成上傳。
CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
相關(guān)文檔
關(guān)于在各類上傳場(chǎng)景中禁止覆蓋同名文件的完整示例代碼,請(qǐng)參見(jiàn)GitHub示例。
關(guān)于在簡(jiǎn)單上傳的API接口說(shuō)明,請(qǐng)參見(jiàn)PutObject。
關(guān)于拷貝文件的API接口說(shuō)明,請(qǐng)參見(jiàn)CopyObject。
關(guān)于分片上傳的API接口說(shuō)明,請(qǐng)參見(jiàn)InitiateMultipartUpload以及CompleteMultipartUpload。