在上载到Azure Blob存储区之前更改IFormFile的文件名

icomxhvb  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(103)

我尝试在将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}", ""));
        }
    }
nkkqxpd9

nkkqxpd91#

如果要修改文件名以在blob容器中创建子目录,可以执行以下操作:

public async Task<BlobResponseDto> UploadWithPrefixAsync(IFormFile blob, string prefix)
    {
        // Create new upload response object that we can return to the requesting method
        BlobResponseDto response = new BlobResponseDto();

        // Get a reference to a container named in appsettings.json and then create it
        BlobContainerClient container = new BlobContainerClient(_storageConnectionString, _storageContainerName);
        //await container.CreateAsync();
        try
        {

            // Get a reference to the blob just uploaded from the API in a container from configuration settings
            BlobClient client = container.GetBlobClient($"{prefix}" + blob.FileName);

            // Open a stream for the file we want to upload
            await using (Stream? data = blob.OpenReadStream())
            {
                // Upload the file async
                await client.UploadAsync(data);
            }

            // Everything is OK and file got uploaded
            response.Status = $"File {blob.FileName} Uploaded Successfully";
            response.Error = false;
            response.Blob.Uri = client.Uri.AbsoluteUri;
            response.Blob.Name = client.Name;

        }
        // If the file already exists, we catch the exception and do not upload it
        catch (RequestFailedException ex)
           when (ex.ErrorCode == BlobErrorCode.BlobAlreadyExists)
        {
            _logger.LogError($"File with name {blob.FileName} already exists in container. Set another name to store the file in the container: '{_storageContainerName}.'");
            response.Status = $"File with name {blob.FileName} already exists. Please use another name to store your file.";
            response.Error = true;
            return response;
        }
        // If we get an unexpected error, we catch it here and return the error message
        catch (RequestFailedException ex)
        {
            // Log error to console and create a new response we can return to the requesting method
            _logger.LogError($"Unhandled Exception. ID: {ex.StackTrace} - Message: {ex.Message}");
            response.Status = $"Unexpected error: {ex.StackTrace}. Check log with StackTrace ID.";
            response.Error = true;
            return response;
        }

        // Return the BlobUploadResponse object
        return response;
    }

我对这个解决方案的灵感来自于阅读了Christian Schou的this伟大文章之后。
快乐编码!

相关问题