Par défaut, le téléchargement d'un objet portant le même nom qu'un objet existant écrase ce dernier. Cette rubrique explique comment configurer l'en-tête de requête x-oss-forbid-overwrite pour empêcher l'écrasement d'objets existants lors de la copie d'objets ou de l'exécution d'un chargement simple ou multipartie.
Notes d'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à Object Storage Service (OSS) via d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison pris en charge par OSS, consultez Régions et points de terminaison.
Les identifiants d'accès utilisés dans cette rubrique sont obtenus à partir des variables d'environnement. Pour plus d'informations, consultez Configuration des identifiants d'accès.
Cette rubrique illustre la création d'une instance
OSSClientavec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification avec des identifiants provenant du Security Token Service (STS), consultez Configuration du client.
Empêcher l'écrasement lors d'un chargement simple
L'exemple de code suivant montre comment empêcher l'écrasement d'objets existants portant le même nom lors d'un chargement simple :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
String objectName = "exampledir/object";
String content = "Hello OSS!";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a PutObjectRequest object.
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// Specify whether to overwrite an existing object with the same name.
// By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported.
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-forbid-overwrite", "true");
putObjectRequest.setMetadata(metadata);
// Upload the local file.
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();
}
}
}
}
Empêcher l'écrasement lors de la copie d'un objet
-
Utilisation de CopyObjectRequest pour copier un petit objet
L'exemple de code suivant montre comment empêcher l'écrasement d'un objet existant par un petit objet portant le même nom lors de la copie à l'aide de
CopyObjectRequest:import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the source bucket. String sourceBucketName = "srcexamplebucket"; // Specify the full path of the source object. Do not include the bucket name in the full path. String sourceObjectName = "srcexampleobject.txt"; // Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. String destinationBucketName = "desexamplebucket"; // Specify the full path of the destination object. Do not include the bucket name in the full path. String destinationObjectName = "desexampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a CopyObjectRequest object. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); // Configure new metadata for the destination object. ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("text/html"); // Specify whether to overwrite the existing object with the same name. // By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported. metadata.setHeader("x-oss-forbid-overwrite", "true"); copyObjectRequest.setNewObjectMetadata(metadata); // Copy the object. 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(); } } } } -
Copie d'un grand objet
L'exemple de code suivant montre comment empêcher l'écrasement d'un objet existant par un grand objet portant le même nom lors d'une copie multipartie :
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the source bucket. String sourceBucketName = "srcexamplebucket"; // Specify the full path of the source object. Do not include the bucket name in the full path. String sourceObjectName = "srcexampleobject.txt"; // Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. String destinationBucketName = "desexamplebucket"; // Specify the full path of the destination object. Do not include the bucket name in the full path. String destinationObjectName = "desexampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. 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); // Query the size of the object that you want to copy. long contentLength = objectMetadata.getContentLength(); // Set the part size to 10 MB. long partSize = 1024 * 1024 * 10; // Calculate the total number of parts. int partCount = (int) (contentLength / partSize); if (contentLength % partSize != 0) { partCount++; } System.out.println("total part count:" + partCount); // Initialize a multipart copy task. You can specify the metadata of the destination object by using InitiateMultipartUploadRequest. InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName); // Specify whether to overwrite the existing object with the same name. // By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported. ObjectMetadata metadata = new ObjectMetadata(); metadata.setHeader("x-oss-forbid-overwrite", "true"); initiateMultipartUploadRequest.setObjectMetadata(metadata); InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest); String uploadId = initiateMultipartUploadResult.getUploadId(); // Start the multipart copy task. List<PartETag> partETags = new ArrayList<PartETag>(); for (int i = 0; i < partCount; i++) { // Calculate the size of each part. long skipBytes = partSize * i; long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes; // Create an UploadPartCopyRequest object. You can specify conditions by using 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); // Store the returned PartETags in partETags. partETags.add(uploadPartCopyResult.getPartETag()); } // Complete the multipart copy task. CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest( destinationBucketName, destinationObjectName, uploadId, partETags); // Specify whether to overwrite the existing object with the same name. // By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten. // If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported. 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(); } } } }
Empêcher l'écrasement lors d'un chargement multipartie
L'exemple de code suivant montre comment empêcher l'écrasement d'un objet existant par un objet portant le même nom lors d'un chargement multipartie :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
String objectName = "exampledir/object";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an InitiateMultipartUploadRequest object.
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
// Specify whether to overwrite the existing object with the same name.
// By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported.
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-forbid-overwrite", "true");
request.setObjectMetadata(metadata);
// Initiate a multipart upload task.
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
// Obtain the upload ID. The upload ID is the unique identifier of the multipart upload task. You can initiate related requests based on the upload ID, such as canceling or querying the multipart upload task.
String uploadId = upresult.getUploadId();
// partETags is a set of PartETags. A PartETag consists of the part number and ETag of an uploaded part
List<PartETag> partETags = new ArrayList<PartETag>();
// Calculate the total number of parts.
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++;
}
// Upload all parts.
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
InputStream instream = new FileInputStream(sampleFile);
// Skip the parts that are uploaded.
instream.skip(startPos);
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(instream);
// Configure the size of each part. Each part except for the last part must be larger than 100 KB.
uploadPartRequest.setPartSize(curPartSize);
// Configure part numbers. Each part is configured with a part number. The value ranges from 1 to 10000. If you configure a number beyond the range, OSS returns the InvalidArgument error code.
uploadPartRequest.setPartNumber( i + 1);
// Parts are not necessarily uploaded in order and can be uploaded from different OSS clients. OSS sorts the parts based on the part numbers and combines the parts into a complete object.
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// After you upload a part, the response includes a PartETag. The PartETag is stored in partETags.
partETags.add(uploadPartResult.getPartETag());
}
// Create a CompleteMultipartUploadRequest object.
// When you complete a multipart upload task, you must provide all valid PartETags. After OSS receives the PartETags, OSS verifies all parts one by one. After all parts are verified, OSS combines the parts into a complete object.
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// Specify whether to overwrite the existing object with the same name.
// By default, if x-oss-forbid-overwrite is not specified, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to false, an existing object with the same name is overwritten.
// If x-oss-forbid-overwrite is set to true, an existing object with the same name is not overwritten. If an object with the same name already exists, an error is reported.
completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true");
// Complete the multipart upload task.
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();
}
}
}
}
Références
Pour consulter l'exemple de code complet utilisé pour empêcher l'écrasement d'objets existants portant le même nom lors du chargement d'objets, rendez-vous sur GitHub.
Pour plus d'informations sur l'opération API permettant d'effectuer un chargement simple, consultez PutObject.
Pour plus d'informations sur l'opération API permettant de copier un objet, consultez CopyObject.
Pour plus d'informations sur les opérations API permettant d'effectuer un chargement multipartie, consultez InitiateMultipartUpload et CompleteMultipartUpload.