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?