Delete media files

Updated at:

ApsaraVideo VOD lets you delete media files to manage storage costs or remove expired or non-compliant content. This topic describes the different types of delete operations and their impact. It also provides instructions on how to safely and efficiently delete media files using the console, API, or software development kit (SDK).

How it works

Before deleting files, you must understand how the operation works and its potential risks to prevent irreversible data loss.

Warning

All delete operations are physical deletions. The files and their associated media asset information are permanently removed and cannot be recovered. To back up your files, see Migrate ApsaraVideo VOD resources.

Delete type

Deleted content

Impact on playback

Full audio or video

The source file, all transcoded streams, thumbnails, and sprites.

The video or audio cannot be played.

Audio and video streams

The transcoded file of a specific definition.

The specific definition cannot be played. This may cause an error in the player.

Source file

The original uploaded file.

The original quality version cannot be played.

Image

The image file.

A video cannot be displayed as a thumbnail.

Note
  • After you delete a media file from ApsaraVideo VOD, the cache on CDN points of presence (POPs) is not automatically purged. You can use the purge feature in the ApsaraVideo VOD console to clear stale data from CDN POPs. For more information, see Refresh and prefetch.

  • By default, you cannot delete an audio or video source file that was uploaded for distribution without transcoding, because it is used for original quality playback. To delete the file, call the DeleteMezzanines operation and specify the Force parameter.

Scenario 1: Delete files using the console

Delete a small number of files manually

The console provides an intuitive interface and is suitable for deleting a small number of files.

  1. Log on to the ApsaraVideo VOD console.

  2. In the navigation pane on the left, choose Media Assets, and then click Audio/Video, Image, or Short Video Material.

  3. On the management page, find the file that you want to delete, and then click Delete in the Actions column.

Delete files in batches through media asset policies

Important
  • Storage and deletion policies apply only to media assets in the ApsaraVideo VOD bucket, and only supports audio and video files with standard storage type. The deletion policy does not apply to media assets that have been stored for less than seven days.

  • Policies run daily from 00:00 to 24:00 (UTC+8) based on upload time. Each policy processes up to 50,000 media assets per day. Excess assets carry over to the next day.

  • A maximum of five media asset deletion policies can be configured. If a media asset matches multiple policies, only the highest-priority policy runs.

  • After the policy is enabled, audio and video will be automatically deleted according to conditions, and cannot be restored after deletion. Please confirm the time condition, classification condition and deletion configuration of the policy before enabling.

  1. Log on to the ApsaraVideo VOD console.

  2. In the left-side navigation pane, choose Configuration Management > Media Management > Policy Management.

  3. On the Policy Management tab, click Create Policy and configure the parameters.

    Parameter

    Description

    Upload Time or Storage Duration

    • Upload Time: Deletes media assets uploaded within the specified time range.

    • Storage Duration: Deletes media assets stored longer than the specified duration.

    Category

    The media asset categories to which the deletion policy applies. Select up to three categories. Media asset categories.

    Note

    Policies can be applied only to first-level categories. Deleting a first-level category does not delete the media assets in its subcategories.

    Storage Class

    The value is fixed. Only media assets of the Standard storage class are supported.

    Bucket

    Fixed. Only the ApsaraVideo VOD bucket is supported.

    Deletion Configuration

    • All Media Resources: The source file and its transcoded files.

    • Transcoded files only: The transcoded output files only.

    • Source File Only: The uploaded source file only.

    Start Date

    The time when the deletion policy starts to take effect.

    Priority

    Higher values indicate higher priority. For policies with equal priority, the earliest-created policy takes precedence.

Scenario 2: Delete files using the API or SDK

Deleting media files using the API or SDK provides greater flexibility and automation. It is the preferred solution for managing many media assets in a production environment.

Note
  • Ensure that you have installed the SDK for your desired language and initialized the client. For more information, see Server-side SDKs.

  • When you call an API operation to delete media files, note the queries per second (QPS) limit. If the QPS limit is exceeded, the API call fails. For more information, see Throttling.

Delete one or more full videos

Note
  • You can delete up to 20 videos at a time.

  • You can accept task completion notifications through DeleteMediaComplete.

This is the most common scenario. Call the DeleteVideo operation to delete all resources related to a video, such as the source file, transcoded streams, and snapshots. The following code provides an example.

from aliyunsdkvod.request.v20170321 import DeleteVideoRequest
from aliyunsdkcore.client import AcsClient
import json

def delete_video_safely(video_ids: str, access_key: str, secret_key: str, region='cn-shanghai'):
    """
    Safely delete one or more videos.
    
    Args:
        video_ids: The IDs of the videos. Separate multiple IDs with commas.
        access_key: The AccessKey ID.
        secret_key: The AccessKey secret.
        region: The region.
    
    Returns:
        dict: A dictionary that indicates whether the call was successful and includes any error messages.
    """
    try:
        # 1. Initialize the client.
        client = AcsClient(access_key, secret_key, region)
        
        # 2. Create a delete request.
        request = DeleteVideoRequest.DeleteVideoRequest()
        request.set_VideoIds(video_ids)
        
        # 3. Execute the deletion.
        response = client.do_action_with_exception(request)
        result = json.loads(response)
        
        print(f"Delete request for videos {video_ids} submitted. RequestID: {result.get('RequestId')}")
        return {"success": True, "data": result}
        
    except Exception as e:
        error_msg = str(e)
        print(f"Deletion failed: {error_msg}")
        
        # Common error handling
        if "InvalidVideo.NotFound" in error_msg:
            return {"success": False, "error": "The video does not exist or has been deleted."}
        elif "Forbidden.IllegalStatus" in error_msg:
            return {"success": False, "error": "The video cannot be deleted due to its current status. It may be undergoing transcoding."}
        elif "Throttling" in error_msg:
            return {"success": False, "error": "The request is too frequent. Please try again later."}
        else:
            return {"success": False, "error": f"Unknown error: {error_msg}"}

# Example usage
# result = delete_video_safely(
#     video_ids="your-video-id-1,your-video-id-2",
#     access_key="your-access-key", 
#     secret_key="your-secret-key"
# )

Delete video streams of a specific definition

Call the DeleteStream operation. You can use this feature when you only need to remove a specific definition but want to keep others. The following code provides an example.

from aliyunsdkvod.request.v20170321 import DeleteStreamRequest
# ... (Reuse the AcsClient initialization from the previous example)

def delete_specific_stream(video_id: str, job_ids: str, access_key: str, secret_key: str):
    """
    Delete the transcoded stream of a specific definition.
    
    Args:
        video_id: The video ID.
        job_ids: The list of transcoding job IDs. Separate multiple IDs with commas.
    """
    try:
        client = AcsClient(access_key, secret_key, 'cn-shanghai')
        request = DeleteStreamRequest.DeleteStreamRequest()
        request.set_VideoId(video_id)
        request.set_JobIds(job_ids)
        
        response = client.do_action_with_exception(request)
        print(f"The specified definition stream for video {video_id} was deleted.")
        return json.loads(response)
        
    except Exception as e:
        print(f"Failed to delete the stream: {e}")
        raise

# Example: Assume you have obtained the JobId 'job-id-for-4k' for the '4K' definition by calling GetPlayInfo.
# delete_specific_stream(
#     video_id="your-video-id",
#     job_ids="job-id-for-4k",
#     access_key="your-access-key",
#     secret_key="your-secret-key"
# )

Force delete a source file

Call the DeleteMezzanines operation. The deletion behavior varies depending on the upload mode:

  • With transcoding enabled: The source file (mezzanine) and the transcoded streams are stored separately. Deleting the source file retains the generated transcoded streams, which can still be played normally.

  • Without transcoding: The mezzanine is the source file itself. Deleting the source file is equivalent to deleting the mezzanine, which causes the playback streams to be removed and unrecoverable.

The following code provides an example.

Important

With transcoding enabled: After you delete the source file, playback in original quality is unavailable, but the transcoded streams are not affected. You cannot transcode the video again after the deletion.

Without transcoding: After you delete the source file, the mezzanine (that is, the source file) is permanently deleted. All playback streams are removed and cannot be recovered. Use this operation only after you confirm that the source file is no longer needed.

from aliyunsdkvod.request.v20170321 import DeleteMezzaninesRequest
# ... (Reuse the AcsClient initialization from the previous example)

def force_delete_source_file(video_ids: str, access_key: str, secret_key: str):
    """
    Force delete the source file.
    
    Args:
        video_ids: The list of video IDs. Separate multiple IDs with commas.
    """
    try:
        client = AcsClient(access_key, secret_key, 'cn-shanghai')
        request = DeleteMezzaninesRequest.DeleteMezzaninesRequest()
        request.set_VideoIds(video_ids)
        request.set_Force(True)  # Force delete flag
        
        response = client.do_action_with_exception(request)
        print("Source file force deleted successfully.")
        print("Purge the CDN cache immediately to prevent 404 errors during original quality playback.")
        return json.loads(response)
        
    except Exception as e:
        print(f"Force deletion failed: {e}")
        raise

# force_delete_source_file(
#     video_ids="your-video-id",
#     access_key="your-access-key",
#     secret_key="your-secret-key"
# )

The DeleteMezzanines operation deletes only the video source file (mezzanine file). After the call succeeds, the API returns a success response, but the video placeholder remains in the media library's audio/video list. A successful API response does not mean that the video has been removed from the list. To completely remove a video entry from the media library, call the DeleteVideo operation instead, which deletes the entire video, including the source file, transcoded stream files, and snapshots.

Delete image files

To delete uploaded images or video snapshots, call the DeleteImage operation.