c# - Azure Blob 容器 - 上传具有相同名称属性的 Blob

标签 c# asp.net .net azure azure-blob-storage

我允许应用程序中的用户在评估运行时将文件附加到评估中。我预见的一个问题是用户将相同的文档附加/上传到不同的评估。这些文件存储在 Azure Blob 存储容器中,并具有自定义元数据属性。

下面是一些显示我的 API 服务的代码:

foreach (var blob in blobs.Files)
                {

                    try
                    {
                        // Get a reference to the blob just uploaded from the API in a container from configuration settings
                        BlobClient client = container.GetBlobClient(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);
                        }

                        Guid guid = Guid.NewGuid();

                        // Set metadata properties
                        var metadata = new Dictionary<string, string>
                        {
                            {"Guid", guid.ToString()},
                            {"UserId", valuation.UserId.ToString()},
                            {"TenantId", valuation.TenantId.ToString()},
                            {"ValuationId", valuation.Id.ToString()}
                        };

                        // Update blob metadata
                        await client.SetMetadataAsync(metadata);

                        Document document = new Document()
                        {
                            Guid = guid.ToString(),
                            FileName = blob.FileName,
                            FileType = blob.ContentType,
                            FileUrl = client.Uri.AbsoluteUri,
                            ValuationId = valuation.Id,
                            UserId = valuation.UserId,
                            TenantId = valuation.TenantId
                        };

                        await _ctx.Document.AddAsync(document);
                        await _ctx.SaveChangesAsync();

                        // Everything is OK and file got uploaded
                        blobResponse.Status = $"File {blob.FileName} Uploaded Successfully";
                        blobResponse.Error = false;
                        blobResponse.Blobs.Add(new BlobDTO
                        {
                            Name = client.Name,
                            Uri = client.Uri.AbsoluteUri
                        });
                    }
                    // If the file already exists, we catch the exception and do not upload it
                    catch (RequestFailedException ex)
                    when (ex.ErrorCode == BlobErrorCode.BlobAlreadyExists)
                    {
                        blobResponse.Status = $"File with name {blob.FileName} already exists. Please use another name to store your file.";
                        blobResponse.Error = true;
                        serviceResponse.Success = false;
                        serviceResponse.Message = "Filename already exists";
                        serviceResponse.Data = blobResponse;
                        return serviceResponse;
                    }
                    catch (Exception ex)
                    {
                        blobResponse.Status = $"Unexpected error: {ex.StackTrace}. Check log with StackTrace ID.";
                        blobResponse.Error = true;
                        serviceResponse.Success = false;
                        serviceResponse.Message = "Unexpected error";
                        serviceResponse.Data = blobResponse;
                    }
                }

可以更改文件名吗?如果不是,我该如何处理这种情况,同时保留文件名供引用?

最佳答案

您可以做的一件事是使用 guid 作为 blob 名称,然后将实际文件名存储为元数据。

您的代码将类似于:

foreach (var blob in blobs.Files)
{

    try
    {

        Guid guid = Guid.NewGuid();
        // Get a reference to the blob just uploaded from the API in a container from configuration settings
        BlobClient client = container.GetBlobClient(guid.ToString());

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

        // Set metadata properties
        var metadata = new Dictionary<string, string>
        {
            {"Guid", guid.ToString()},
            {"UserId", valuation.UserId.ToString()},
            {"TenantId", valuation.TenantId.ToString()},
            {"ValuationId", valuation.Id.ToString()},
            {"FileName", blob.FileName}
        };

        // Update blob metadata
        await client.SetMetadataAsync(metadata);

        Document document = new Document()
        {
            Guid = guid.ToString(),
            FileName = blob.FileName,
            FileType = blob.ContentType,
            FileUrl = client.Uri.AbsoluteUri,
            ValuationId = valuation.Id,
            UserId = valuation.UserId,
            TenantId = valuation.TenantId
        };

        await _ctx.Document.AddAsync(document);
        await _ctx.SaveChangesAsync();

        // Everything is OK and file got uploaded
        blobResponse.Status = $"File {blob.FileName} Uploaded Successfully and saved as {guid.ToString()}";
        blobResponse.Error = false;
        blobResponse.Blobs.Add(new BlobDTO
        {
            Name = client.Name,
            Uri = client.Uri.AbsoluteUri
        });
    }
    // If the file already exists, we catch the exception and do not upload it
    catch (RequestFailedException ex)
    when (ex.ErrorCode == BlobErrorCode.BlobAlreadyExists)
    {
        blobResponse.Status = $"File with name {blob.FileName} already exists. Please use another name to store your file.";
        blobResponse.Error = true;
        serviceResponse.Success = false;
        serviceResponse.Message = "Filename already exists";
        serviceResponse.Data = blobResponse;
        return serviceResponse;
    }
    catch (Exception ex)
    {
        blobResponse.Status = $"Unexpected error: {ex.StackTrace}. Check log with StackTrace ID.";
        blobResponse.Error = true;
        serviceResponse.Success = false;
        serviceResponse.Message = "Unexpected error";
        serviceResponse.Data = blobResponse;
    }
}

关于c# - Azure Blob 容器 - 上传具有相同名称属性的 Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76093708/

相关文章:

来自 C++ 的 C# 回调提供访问冲突

c# - 如何禁用 Windows Media Player 中的右键单击

c# - 'Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment' 的类型初始值设定项抛出异常

javascript - 未捕获的范围错误: Maximum call stack size exceeded in Chrome

c# - Windows 窗体 : detect the change of the focused control

.NET Find Eaten 异常

java - 将c#函数代码转换为java

c# - 是否可以设计一个 C# 类,在通过反射查询时将其自身标记为正 IsValueType 和正 IsClass?

asp.net - 将 Web 表单转换为 Razor,没有任何错误

asp.net - 如何预热 ASP.NET Web 应用程序,以便导航到时启动时间不会太长?