0

I am uploading file to blob storage using following code. For a given file, I want to set expiration time. After which system should automatically delete the file.

[HttpPost("UploadFile")]
public async Task<IActionResult> UploadFile([FromForm] IFormFile file)
{
    if (file == null || file.Length <= 0)
        return BadRequest("File is required.");

    try
    {
        // Create a unique filename to avoid conflicts
        string fileName = Guid.NewGuid().ToString() + "_" + file.FileName;

        // Upload the file to Azure Blob Storage
        BlobServiceClient blobServiceClient = new BlobServiceClient(_connectionString);
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_containerName);
        BlobClient blobClient = containerClient.GetBlobClient(fileName);

        using (var stream = file.OpenReadStream())
        {
            await blobClient.UploadAsync(stream, overwrite: true);
        }

        // Set the retention policy for the blob (30 days)
        var metadata = new Dictionary<string, string>
        {
            { "retention-days", "30" }
        };

        await blobClient.SetMetadataAsync(metadata);

        return Ok("File uploaded successfully.");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"An error occurred: {ex.Message}");
    }
}

With this code, I am able to upload the file but getting error "The metadata specified is invalid. It has characters that are not permitted" while setting retention period.

I also tried this code but getting same error:

  BlobProperties properties = await blobClient.GetPropertiesAsync();
            properties.Metadata.Add("retention-days", "30");
            await blobClient.SetMetadataAsync(properties.Metadata);

How can I ensure I am able to delete a file in azure blob storage after X number of days?

OpenStack
  • 5,048
  • 9
  • 34
  • 69

1 Answers1

0

If you refer to this for the allowed naming for the metadata keys. '-' is not an allowed character and hence your error message.

If you refer to this documentation, it states that the metadata you need to use is "RetentionDays". I have tested the metadata update successfully, but I have not tested the auto deletion of the blob based on this metadata. You can test this yourself and either close or comment on this question accordingly.

Also, you are uploading the blob and then setting the metadata. You can do this in 1 step. Refer to this existing SO answer to see how to do this.

Anupam Chand
  • 2,209
  • 1
  • 5
  • 14