gpt4 book ai didi

c# - 如何将文件上传到 blob 存储并从附件中的 cosmosdb 文档引用它

转载 作者:行者123 更新时间:2023-12-02 07:46:55 25 4
gpt4 key购买 nike

我是 CosmosDb 和 azure blob 存储的新手,根据要求,我需要引用从 CosmosDb 中的文档上传到 azure blob 存储的文件,并在附件部分使用它来保存元数据。

我知道json元数据结构应该是这样的:

{    
"id":"image13d65101-90c4-4c2a-a423-fbf221c73233",
"contentType":"image/jpg",
"media":"www.bing.com",
"_rid":"rnYYAMVFUAUBAAAAAAAAAEC+LNM=",
"_ts":1408056025,
"_self":"dbs\/rnYYAA==\/colls\/rnYYAMVFUAU=\/docs\/rnYYAMVFUAUBAAAAAAAAAA==\/attachments\/rnYYAMVFUAUBAAAAAAAAAEC+LNM=",
"_etag":"00002a00-0000-0000-0000-53ed3ad90000"
}

但是,在将文件上传到 azure blob 存储时,如何获取对媒体属性的引用,更准确地说,如何将文件从 c# 上传到 azure blob 存储,并通过将 url 设置为媒体属性来引用它。

最佳答案

下面是我的一个应用程序中的示例代码,用于上传到 blob 存储,然后将对 cosmosdb 的引用保存为 uri,

    public async Task<IActionResult> UploadImageAsync([FromBody] ImageUploadRequest imageRequest)
{

if (string.IsNullOrEmpty(imageRequest?.Base64))
{
return BadRequest();
}

var tokens = imageRequest.Base64.Split(',');
var ctype = tokens[0].Replace("data:", "");
var base64 = tokens[1];
var content = Convert.FromBase64String(base64);

// Upload photo to storage...
var blobUri = await UploadImageToStorage(content);

// Then create a Document in CosmosDb to notify our Function
var identifier = await UploadDocument(blobUri, imageRequest.Name ?? "Bob");

return Ok(identifier);
}

private async Task<Guid> UploadDocument(Uri uri, string imageName)
{

var endpoint = new Uri(_settings.ImageConfig.CosmosUri);
var auth = _settings.ImageConfig.CosmosKey;
var client = new DocumentClient(endpoint, auth);
var identifier = Guid.NewGuid();

await client.CreateDatabaseIfNotExistsAsync(new Database() { Id = dbName });
await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(dbName),
new DocumentCollection { Id = colName });

await client.CreateDocumentAsync(
UriFactory.CreateDocumentCollectionUri(dbName, colName),
new ImageDocument
{
Id = identifier,
IsApproved = null,
PetName = petName,
MediaUrl = uri.ToString(),
Created = DateTime.UtcNow
});

return identifier;
}

private async Task<Uri> UploadImageToStorage(byte[] content)
{
var storageName = _settings.PetsConfig.BlobName;
var auth = _settings.PetsConfig.BlobKey;
var uploader = new PhotoUploader(storageName, auth);
var blob = await uploader.UploadPetPhoto(content);
return blob.Uri;
}

关于c# - 如何将文件上传到 blob 存储并从附件中的 cosmosdb 文档引用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996696/

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