我尝试在将IFormFile上载到Azure Blob存储之前更改其文件名,但当前解决方案不起作用
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}", ""));
}
}
有什么建议吗?
解决方案
问题是我对文件上传的误解,如果你有兴趣用不同的名字保存文件,你应该把它放在行
BlobClient client = _client.GetBlobClient($"{name}{format}");
完整的解决方案
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}", ""));
}
}
1条答案
按热度按时间nkkqxpd91#
如果要修改文件名以在blob容器中创建子目录,可以执行以下操作:
我对这个解决方案的灵感来自于阅读了Christian Schou的this伟大文章之后。
快乐编码!