Tous les produits
Search
Centre de documentation

Object Storage Service:Prevent objects with the same name from being overwritten (Android SDK)

Dernière mise à jour :Sep 22, 2026

Par défaut, le téléversement d’un objet portant le même nom qu’un objet existant écrase ce dernier si vous disposez des autorisations d’accès requises. Cette rubrique explique comment définir l’en-tête de requête x-oss-forbid-overwrite pour empêcher l’écrasement des objets lors de téléversements simples, de copies d’objets et de téléversements en plusieurs parties.

Remarques sur l’utilisation

  • Avant d’exécuter l’exemple de code présenté dans cette rubrique, créez une instance OSSClient en utilisant un nom de domaine personnalisé ou le Security Token Service (STS). Pour plus d’informations, consultez la section Initialisation (SDK Android).

Téléversement simple

L’exemple de code suivant montre comment empêcher l’écrasement d’objets existants par des objets portant le même nom lors d’un téléversement simple :

// Enter the bucket name. Example: examplebucket. For more information about bucket naming conventions, see Buckets.
String bucketName = "examplebucket";
// Enter the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt. For more information about object naming conventions, see Objects.
String objectKey = "exampledir/exampleobject.txt";
// Enter the full path of the local file to upload.
String localFile = "/storage/emulated/0/oss/examplefile.txt";
// Create an upload request.
PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, localFile);
ObjectMetadata metadata = new ObjectMetadata();

// Specify whether to overwrite an object with the same name during the upload.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
put.setMetadata(metadata);

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network error.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A server-side exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Copie de fichiers

L’exemple de code suivant illustre comment empêcher l’écrasement d’un objet existant dans un bucket par un objet portant le même nom lors d’une copie :

// Enter the source bucket name.
String srcBucketName = "srcbucket";
// Enter the full path of the source object in the bucket.
String srcObjectKey = "dir1/srcobject.txt";
// Enter the destination bucket name.
String destBucketName = "destbucket";
// Enter the full path of the destination object in the bucket.
String destObjectKey = "dir2/destobject.txt";
// Create a copy request.
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey, destBucketName, destObjectKey);

ObjectMetadata metadata = new ObjectMetadata();

// Specify whether to overwrite an object with the same name during the copy operation.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
copyObjectRequest.setNewObjectMetadata(metadata);

// Copy the object asynchronously.
OSSAsyncTask copyTask = oss.asyncCopyObject(copyObjectRequest, new OSSCompletedCallback<CopyObjectRequest, CopyObjectResult>() {
    @Override
    public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
        Log.d("copyObject", "copy success!");
    }

    @Override
    public void onFailure(CopyObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network error.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Téléversement en plusieurs parties

L’exemple de code suivant montre comment empêcher l’écrasement d’un objet existant lorsque vous utilisez un téléversement en plusieurs parties pour téléverser un objet portant le même nom :

// Enter the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Enter the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt.
String objectKey = "exampledir/exampleobject.txt";
// Enter the full path of the local file to upload.
String localFile = "/storage/emulated/0/oss/examplefile.txt";

// Initialize the multipart upload.
InitiateMultipartUploadRequest init = new InitiateMultipartUploadRequest(bucketName, objectKey);
ObjectMetadata metadata = new ObjectMetadata();
// Specify whether to overwrite an object with the same name during the upload.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
init.setMetadata(metadata);

InitiateMultipartUploadResult initResult = oss.initMultipartUpload(init);
// The uploadId is returned. The uploadId is the unique identifier for the multipart upload event. You can use this uploadId to perform related operations, such as canceling or querying the multipart upload.
String uploadId = initResult.getUploadId();

// Set the size of a single part in bytes. The value must be in the range of 100 KB to 5 GB.
int partCount = 100 * 1024;
// Upload parts.
List<PartETag> partETags = new ArrayList<PartETag>();
for (int i = 1; i < 5; i++) {
    byte[] data = new byte[partCount];

    RandomAccessFile raf = new RandomAccessFile(localFile, "r");
    long skip = (i-1) * partCount;
    raf.seek(skip);
    raf.readFully(data, 0, partCount);

    UploadPartRequest uploadPart = new UploadPartRequest();
    uploadPart.setBucketName(bucketName);
    uploadPart.setObjectKey(objectKey);
    uploadPart.setUploadId(uploadId);
    // Set the part number. Part numbers start from 1. Each uploaded part has a part number. The value must be in the range of 1 to 10,000.
    uploadPart.setPartNumber(i);
    uploadPart.setPartContent(data);
    try {
        UploadPartResult result = oss.uploadPart(uploadPart);
        PartETag partETag = new PartETag(uploadPart.getPartNumber(), result.getETag());
        partETags.add(partETag);
    } catch (ServiceException serviceException) {
        OSSLog.logError(serviceException.getErrorCode());
    }
}
Collections.sort(partETags, new Comparator<PartETag>() {
    @Override
    public int compare(PartETag lhs, PartETag rhs) {
        if (lhs.getPartNumber() < rhs.getPartNumber()) {
            return -1;
        } else if (lhs.getPartNumber() > rhs.getPartNumber()) {
            return 1;
        } else {
            return 0;
        }
    }
});

// Complete the multipart upload.
CompleteMultipartUploadRequest complete = new CompleteMultipartUploadRequest(bucketName, objectKey, uploadId, partETags);
metadata = new ObjectMetadata();
// Specify whether to overwrite an object with the same name when you complete the upload.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
complete.setMetadata(metadata);
CompleteMultipartUploadResult completeResult = oss.completeMultipartUpload(complete);           

Références

  • Pour plus d’informations sur l’opération API permettant d’effectuer un téléversement simple, consultez la section PutObject.

  • Pour plus d’informations sur l’opération API permettant de copier un objet, consultez la section CopyObject.

  • Pour savoir comment initialiser une instance OSSClient, consultez la section Initialisation.

  • Un téléversement en plusieurs parties implique trois opérations API. Pour plus d’informations sur ces opérations, consultez les rubriques suivantes :

    • Pour une description de l’opération API permettant d’initialiser un téléversement en plusieurs parties, consultez la section InitiateMultipartUpload.

    • Pour plus d’informations sur l’opération API permettant de téléverser une partie d’un téléversement en plusieurs parties, consultez la section UploadPart.

    • Pour plus d’informations sur l’opération API permettant de finaliser un téléversement en plusieurs parties, consultez la section CompleteMultipartUpload.