Faced with an unexpected problem when uploading a .docx file to a blob container. On the line where I upload the file to the blob container, I get a System.AggregateException. Through trial and error, I found out that it was a reaction to the Cyrillic alphabet in the file name. How can I fix it?
Uploading code:
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Cors;
using Azure.Storage.Blobs.Models;
using System.IO;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace DocxSender.API.Controllers
{
[ApiController]
[Route("api/upload")]
public class UploadController : Controller
{
private readonly IConfiguration _config;
public UploadController(IConfiguration config)
{
_config = config;
}
[HttpPost]
public async Task<IActionResult> Upload([FromForm] IFormFile file, [FromForm] string userEmail)
{
// Get Blob settings
string containerConnectionString = _config.GetValue<string>("ConnectionString");
string blobName = _config.GetValue<string>("BlobName");
// Generate unique File Name for Blob
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(file.FileName);
BlobServiceClient blobServiceClient = new BlobServiceClient(containerConnectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(blobName);
BlobClient blobClient = containerClient.GetBlobClient(fileName + extension);
var metadata = new Dictionary<string, string>
{
{ "Email", userEmail },
{ "UserFileName", file.FileName }
};
try
{
// Upload the stream to the blob with the metadata
await blobClient.UploadAsync(file.OpenReadStream(), new BlobUploadOptions()
{
Metadata = metadata
});
return Ok();
}
catch (Exception ex)
{
return StatusCode(500, $"Error uploading file: {ex.Message}");
}
}
}
}
>Solution :
If you read the error message, you will notice that the reason you are getting this error is because one of the metadata (UserFileName) value contains invalid characters.
Metadata name/value which are included in the request headers can only contain ASCII characters.
One possible way of solving this problem is to convert the UserFileName metadata value to a Base64 encoded string and then save it as metadata.
