-
Notifications
You must be signed in to change notification settings - Fork 1
/
DocumentStore.cs
65 lines (49 loc) · 1.8 KB
/
DocumentStore.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
public class DocumentStore
{
private StorageOptions _storageOptions;
public DocumentStore(StorageOptions storageOptions)
{
_storageOptions = storageOptions;
}
public async Task<string> Store(string path)
{
var client = GetContainer();
var filename = Guid.NewGuid().ToString("N");
var sas = GetWriteSAS(client, filename);
await UploadAsync(sas, path);
return filename;
}
public string GetAccessUrl(string url)
{
var client = GetContainer();
return GetReadSAS(client, url).AbsoluteUri;
}
private BlobContainerClient GetContainer()
{
var connectionString = "DefaultEndpointsProtocol=https;" +
$"AccountName={_storageOptions.AccountName};" +
$"AccountKey={_storageOptions.AccountKey};" +
$"EndpointSuffix={_storageOptions.EndpointSuffix}";
BlobServiceClient service = new BlobServiceClient(connectionString);
return service.GetBlobContainerClient(_storageOptions.ContainerName);
}
private Uri GetWriteSAS(BlobContainerClient containerClient, string filename)
{
var blobClient = containerClient.GetBlobClient(filename);
return blobClient
.GenerateSasUri(BlobSasPermissions.Write, DateTimeOffset.UtcNow.AddMinutes(5));
}
private Uri GetReadSAS(BlobContainerClient containerClient, string filename)
{
var blobClient = containerClient.GetBlobClient(filename);
return blobClient
.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddMinutes(5));
}
private async Task UploadAsync(Uri sas, string path)
{
BlobClient blobClient = new BlobClient(sas, null);
await blobClient.UploadAsync(path);
}
}