如何将文件上传到Blob存储并从附件中的cosmosdb文档引用 [英] How upload file to blob storage and reference it from cosmosdb document in attachment
问题描述
我是CosmosDb和Azure Blob存储的新手,根据需要,我需要引用从CosmosDb中的文档上传到Azure Blob存储的文件,并在附件部分中使用它来保存元数据.
I'm new to CosmosDb and azure blob storage, as a requirement I need to reference a file uploaded to azure blob storage from a document in CosmosDb and use it in the attachment section to save the metadata.
我知道json元数据结构应该是这样的:
I know the json metadata stucture should be like this:
{
"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设置为media属性来引用它./p>
but how can I get a reference to the media property when uploading the file to azure blob storage, more accurately how do I upload a file from c# to azure blob storage and reference it by setting the url to the media property.
推荐答案
这是我的一个应用程序中的示例代码,可以上传到blob存储,然后将对cosmosdb的引用保存为uri,
Here is a sample code from one of my application to upload to blob storage and then save the reference to the cosmosdb as a 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;
}
这篇关于如何将文件上传到Blob存储并从附件中的cosmosdb文档引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!