Por padrão, ao fazer upload de um objeto com o mesmo nome de um objeto já existente, o objeto enviado substitui o existente. Este tópico descreve como configurar o cabeçalho x-oss-forbid-overwrite para impedir a substituição de objetos por outros de mesmo nome em cópias, uploads simples ou multipart.
Observações de uso
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o Object Storage Service (OSS) por meio de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regions and endpoints.
O código deste tópico obtém as credenciais de acesso a partir de variáveis de ambiente. Para mais informações, consulte 配置访问凭证.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Client configuration.
Impedir a substituição em uma tarefa de upload simples
O exemplo de código a seguir mostra como impedir a substituição de objetos existentes por outros com o mesmo nome ao fazer um upload simples:
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();
}
}
}
}
Impedir a substituição em uma tarefa de cópia de objetos
-
Usar o CopyObjectRequest para copiar um objeto pequeno
O exemplo de código a seguir mostra como impedir a substituição de um objeto existente por um objeto pequeno com o mesmo nome ao copiá-lo com o 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(); } } } } -
Copiar um objeto grande
O exemplo de código a seguir mostra como impedir a substituição de um objeto existente por um objeto grande com o mesmo nome ao usar a cópia multipart:
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(); } } } }
Impedir a substituição em uma tarefa de upload multipart
O exemplo de código a seguir mostra como impedir a substituição de um objeto existente por outro com o mesmo nome ao usar o upload multipart:
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();
}
}
}
}
Referências
Para acessar o código de exemplo completo que impede a substituição de objetos existentes por outros com o mesmo nome durante o upload de objetos, visite o GitHub.
Para mais detalhes sobre a operação de API para fazer um upload simples, consulte PutObject.
Para saber mais sobre a operação de API para copiar um objeto, consulte CopyObject.
Para obter mais informações sobre as operações de API para fazer um upload multipart, consulte InitiateMultipartUpload e CompleteMultipartUpload.