Elimine un objeto individual, varios objetos o los objetos que tengan un prefijo de nombre específico dentro de un bucket con control de versiones habilitado.
Notas de uso
En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.
Las credenciales de acceso de este tema se obtienen a partir de variables de entorno. Para más información, consulte 配置访问凭证.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.
Para eliminar un objeto, necesita el permiso
oss:DeleteObject. Para más información, consulte Grant a custom policy.
Comportamiento de eliminación en buckets con control de versiones
Al eliminar un objeto de un bucket con control de versiones, debe decidir si especifica un identificador de versión.
-
Eliminar un objeto sin especificar un identificador de versión (eliminación temporal)
Si no especifica un identificador de versión, OSS no elimina la versión actual. En su lugar, agrega un marcador de eliminación como la versión más reciente. Las solicitudes GetObject posteriores devuelven
404 Not Foundjunto conheader:x-oss-delete-marker = truey el valorx-oss-version-iddel marcador de eliminación en la respuesta.Cuando
x-oss-delete-markeres verdadero,x-oss-version-iddevuelve el identificador de versión del marcador de eliminación. -
Eliminar un objeto al especificar un identificador de versión (eliminación permanente)
Si especifica un identificador de versión, OSS elimina permanentemente esa versión mediante el parámetro
versionIdenparams. Para eliminar la versión con identificador nulo, establezcaparams['versionId'] = "null"enparams. OSS interpreta la cadena "null" como el identificador de versión de destino.
Eliminar un objeto
Elimine un objeto de forma permanente o temporal de un bucket con control de versiones.
-
Eliminar permanentemente un objeto de un bucket con control de versiones habilitado
Elimine un objeto de forma permanente al especificar su identificador de versión:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****"; // 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 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 { // Delete the specified version of the object. ossClient.deleteVersion(bucketName, objectName , versionId); } 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(); } } } } -
Eliminar temporalmente un objeto de un bucket con control de versiones habilitado
Elimine un objeto de forma temporal sin especificar un identificador de versión:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 endpoint of the region in which the bucket is located. For example, if your 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 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 { // Temporarily delete the object. A delete marker is added to the object. ossClient.deleteObject(bucketName, objectName); } 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(); } } } }
Eliminar varios objetos
Elimine varios objetos de forma permanente o temporal de un bucket con control de versiones.
-
Eliminar permanentemente varios objetos de un bucket con control de versiones habilitado
Elimine varios objetos o marcadores de eliminación de forma permanente al especificar sus identificadores de versión:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.DeleteVersionsRequest; import com.aliyun.oss.model.DeleteVersionsResult; import java.net.URLDecoder; 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 paths of the objects. Do not include the bucket name in the full paths. String objectName = "exampledir/object"; String object2Name = "exampledir/object2"; String yourObjectNameVersionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****"; String yourObject2DelMarkerNameVersionId = "MGE3N2M1YgICAof2D0BYiID3N2M1YTITI1NDQzOGY5NTN2M1YTI1NDQz****"; // Specify the region of the bucket. For example, if your 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 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 { // Delete the objects or delete markers that have specified version IDs. List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>(); keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(objectName,yourObjectNameVersionId)); keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(object2Name,yourObject2DelMarkerNameVersionId)); DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName); delVersionsRequest.setKeys(keyVersionsList); // Initiate a deleteVersions request. DeleteVersionsResult delVersionsResult = ossClient.deleteVersions(delVersionsRequest); // View the deletion result. for (DeleteVersionsResult.DeletedVersion delVer : delVersionsResult.getDeletedVersions()) { String keyName = URLDecoder.decode(delVer.getKey(), "UTF-8"); String keyVersionId = delVer.getVersionId(); String keyDelMarkerId = delVer.getDeleteMarkerVersionId(); System.out.println("delete key: " + keyName); System.out.println("delete key versionId: " + keyVersionId); if(keyDelMarkerId != null && keyDelMarkerId.length() != 0){ System.out.println("delete key del_marker versionId: " + keyDelMarkerId); } } } 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(); } } } } -
Eliminar temporalmente varios objetos de un bucket con control de versiones habilitado
Elimine varios objetos de forma temporal sin especificar identificadores de versión:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.DeleteObjectsRequest; import com.aliyun.oss.model.DeleteObjectsResult; import java.net.URLDecoder; 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 paths of the objects. Do not include the bucket name in the full paths. String objectName = "exampledir/object"; String object2Name = "exampledir/object2"; // Specify the region of the bucket. For example, if your 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 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 { // Delete multiple objects at a time. List<String> KeysList = new ArrayList<String>(); KeysList.add(objectName); KeysList.add(object2Name); DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName); request.setKeys(KeysList); // Initiate a deleteObjects request. DeleteObjectsResult delObjResult = ossClient.deleteObjects(request); // View the deletion result. for (String o : delObjResult.getDeletedObjects()) { String keyName = URLDecoder.decode(o, "UTF-8"); System.out.println("delete key name: " + keyName); } } 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(); } } } }
Eliminar objetos por prefijo
Elimine todas las versiones de los objetos que coincidan con un prefijo de nombre específico:
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 bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix.
String prefix = "yourkeyPrefix";
// Specify the region of the bucket. For example, if your 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 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 {
// List the versions of all objects whose names contain the specified prefix and delete the versions.
String nextKeyMarker = null;
String nextVersionMarker = null;
VersionListing versionListing = null;
do {
ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
.withBucketName(bucketName)
.withKeyMarker(nextKeyMarker)
.withVersionIdMarker(nextVersionMarker)
.withPrefix(prefix);
versionListing = ossClient.listVersions(listVersionsRequest);
if (versionListing.getVersionSummaries().size() > 0) {
List<DeleteVersionsRequest.KeyVersion> keyVersionsList = new ArrayList<DeleteVersionsRequest.KeyVersion>();
for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
System.out.println("key name: " + ossVersion.getKey());
System.out.println("versionid: " + ossVersion.getVersionId());
System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
keyVersionsList.add(new DeleteVersionsRequest.KeyVersion(ossVersion.getKey(), ossVersion.getVersionId()));
}
DeleteVersionsRequest delVersionsRequest = new DeleteVersionsRequest(bucketName).withKeys(keyVersionsList);
ossClient.deleteVersions(delVersionsRequest);
}
nextKeyMarker = versionListing.getNextKeyMarker();
nextVersionMarker = versionListing.getNextVersionIdMarker();
} while (versionListing.isTruncated());
} 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();
}
}
}
}
Referencias
Para más información sobre la operación de API que permite eliminar un objeto, consulte DeleteObject.
Para más información sobre la operación de API que permite eliminar varios objetos, consulte DeleteMultipleObjects.