gpt4 book ai didi

c# - 将文件上传到 Azure Blob 存储后一小段时间出现 404

转载 作者:行者123 更新时间:2023-12-04 07:52:29 24 4
gpt4 key购买 nike

我将附件上传到 Azure Blob 存储。我还在上传时创建了一个 SAS-Token;我检索唯一的 URL,将其发送到浏览器并立即打开它。

当我这样做时,我经常(但并非总是)检索到该资源不存在的 404。几秒钟后刷新页面时,它会被正确检索。

看来我上传附件后“太快了”。有没有办法等到 Azure 准备好提供附件?我本以为等待电话就足以实现这一目标。

public async void UploadFile(string filename, byte[] filecontent)
{
var containerClient = _blobServiceclient.GetBlobContainerClient("attachments");
var blobClient = containerClient.GetBlobClient(filename);

using (var stream = new MemoryStream(filecontent))
{
await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = GetContentTypeByFilename(filename) });
}
}


public async Task<string> GetLinkForFile(string filename)
{
var containerClient = _blobServiceclient.GetBlobContainerClient("attachments");

var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = filename,
Resource = "b",
StartsOn = DateTime.UtcNow.AddMinutes(-1),
ExpiresOn = DateTime.UtcNow.AddMinutes(5),
};

// Specify read permissions
sasBuilder.SetPermissions(BlobSasPermissions.Read);

var credentials = new StorageSharedKeyCredential(_blobServiceclient.AccountName, _accountKey);
var sasToken = sasBuilder.ToSasQueryParameters(credentials);

// Construct the full URI, including the SAS token.
UriBuilder fullUri = new UriBuilder()
{
Scheme = "https",
Host = string.Format("{0}.blob.core.windows.net", _blobServiceclient.AccountName),
Path = string.Format("{0}/{1}", containerName, filename),
Query = sasToken.ToString()
};

return fullUri.ToString();
}



public async Task<Document> GetInvoice(byte[] invoiceContent, string invoiceFilename)
{
string filePath = await GetLinkForFile(invoiceFilename);
UploadFile(invoiceFilename, file);

return new Document()
{
Url = filePath
};
}

方法 GetInvoice 由 REST 调用,响应(包含 URL)返回到打开该方法的浏览器。

最佳答案

如果您注意到,您并不是在等待上传操作完成:

_azureStorageRepository.UploadFile(invoiceFilename, file);

请将其更改为:

await _azureStorageRepository.UploadFile(invoiceFilename, file);

并且您不应该看到 404 错误。 Azure Blob 存储具有强一致性。

此外,将 UploadFile 方法从 public async void UploadFile 更改为 public async Task UploadFile,如 @Fildor 在评论中提到的。

关于c# - 将文件上传到 Azure Blob 存储后一小段时间出现 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66884111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com