I am trying change filename for IFormFile before uploading it to azure blob storage but my current solution is not working
public async Task<ExecuteResult> UploadAsync(string name, IFormFile file, CancellationToken cancellationToken)
{
try
{
using (var fileStream = new FileStream(Path.Combine("", name), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
BlobClient client = _client.GetBlobClient(file.FileName);
await using (Stream? data = file.OpenReadStream())
{
await client.UploadAsync(data, true, cancellationToken);
}
return ExecuteResult.Success();
}
catch (RequestFailedException ex)
when (ex.ErrorCode == BlobErrorCode.BlobAlreadyExists)
{
await UploadFileAsync(file, cancellationToken);
return ExecuteResult.Success();
}
catch (RequestFailedException ex)
{
return ExecuteResult.Fail(new Error($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}", ""));
}
}
Any suggestions on how to fix it ?
SOLUTION
The problem is my misunderstanding of the file upload, if you are interested in saving the file under a different name you should put it in the line
BlobClient client = _client.GetBlobClient($"{name}{format}");
Complete solution
public async Task<ExecuteResult> UploadAsync(string name, IFormFile file, CancellationToken cancellationToken)
{
try
{
string format = Path.GetExtension(file.FileName);
BlobClient client = _client.GetBlobClient($"{name}{format}");
await using (Stream? data = file.OpenReadStream())
{
await client.UploadAsync(data, true, new CancellationToken());
}
return ExecuteResult.Success();
}
catch (RequestFailedException ex)
{
return ExecuteResult.Fail(new Error($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}", ""));
}
}
SOLUTION
The problem is my misunderstanding of the file upload, if you are interested in saving the file under a different name you should put it in the line
BlobClient client = _client.GetBlobClient($"{name}{format}");
Complete solution
public async Task<ExecuteResult> UploadAsync(string name, IFormFile file,
CancellationToken cancellationToken)
{
try
{
string format = Path.GetExtension(file.FileName);
BlobClient client = _client.GetBlobClient($"{name}{format}");
await using (Stream? data = file.OpenReadStream())
{
await client.UploadAsync(data, true, new CancellationToken());
}
return ExecuteResult.Success();
}
catch (RequestFailedException ex)
{
return ExecuteResult.Fail(new Error($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}", ""));
}
}