You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

上传至Azure Blob Storage前修改IFormFile文件名失败,求解决方案

问题

尝试在将IFormFile上传至Azure Blob Storage之前修改文件名,但当前实现方案无法正常工作,以下是我的代码:

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}", ""));
    }
}

问题原因

原代码的核心问题是上传Blob时仍使用file.FileName作为存储名称,没有启用自定义的name参数;同时存在多余的本地文件写入逻辑,上传Blob无需预先将文件保存到本地,直接读取IFormFile的流即可完成上传。

解决方案

修改BlobClient的创建逻辑,结合传入的name和原文件扩展名生成新的Blob名称,同时移除不必要的本地文件操作。

完整修复代码

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, cancellationToken);
        }

        return ExecuteResult.Success();
    }
    catch (RequestFailedException ex)
    {
        return ExecuteResult.Fail(new Error($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}", ""));
    }
}

关键修改说明

  • 移除本地文件写入逻辑,直接通过IFormFile.OpenReadStream()获取文件流上传,减少不必要的IO操作
  • 创建BlobClient时使用$"{name}{format}"作为Blob名称,既实现自定义文件名,又保留原文件的扩展名
  • 上传时传入方法参数中的cancellationToken,保证取消令牌的有效性

内容的提问来源于stack exchange,提问作者BraveGio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:54:24