c# sastoken方式访问微软blob,生成sastoken,自定义有效期及访问权限
public class BlobHelperBySas
{
private static CloudStorageAccount storageAccount = null;
private static string filesharebase = "";
private static CloudBlobClient blobClient = null;
static BlobHelperBySas()
{
var authSasToken = ConfigurationManager.AppSettings["blobsasconnectionstring"];
var blobAccountName = ConfigurationManager.AppSettings["blobaccountname"];
StorageCredentials accountSAS = new StorageCredentials(authSasToken);
// Use these credentials and the account name to create a Blob service client.
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, blobAccountName, endpointSuffix: null, useHttps: true);
blobClient = accountWithSAS.CreateCloudBlobClient();
var url = blobClient.BaseUri.ToString();
if (url.LastIndexOf("/").Equals(url.Length - 1))
{
url = url.Substring(0, url.Length - 1);
}
filesharebase = url;
}
/// <summary>
/// 上传本地文件到blobfileshare
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="toPath">blob路径</param>
public static void UploadFileToBlob(string localPath, string toPath)
{
UploadFile(toPath, localPath: localPath);
}
/// <summary>
/// 上传文件流到blob
/// </summary>
/// <param name="stream"></param>
/// <param name="streamLength"></param>
/// <param name="toPath"></param>
public static void UploadStreamToBlob(Stream stream, int streamLength, string toPath)
{
UploadFile(toPath, 2, stream: stream, length: streamLength);
}
/// <summary>
/// 上传文件流到blob
/// </summary>
/// <param name="stream"></param>
/// <param name="streamLength"></param>
/// <param name="toPath"></param>
public static void UploadByteToBlob(byte[] by, int length, string toPath)
{
UploadFile(toPath, 3, by: by, length: length);
}
/// <summary>
/// 上传文件到blob 1物理路径上传 2文件流上传
/// </summary>
/// <param name="toPath"></param>
/// <param name="uploadType"></param>
/// <param name="localPath">本地物理路径</param>
public static void UploadFile(string toPath, int uploadType = 1, string localPath = "", Stream stream = null, int length = 0, byte[] by = null)
{
var splitArrs = toPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
if (!container.Exists())
{
container.Create();
}
var splitLs = splitArrs.ToList();
splitLs.RemoveAt(0);
var blobpath = string.Join("/", splitLs.ToArray());
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
if (uploadType == 1)
{
if (string.IsNullOrEmpty(localPath))
{
throw new Exception("上传类型为本地文件上传时,物理路径不能为空");
}
cloudBlockBlob.UploadFromFileAsync(localPath);
}
else if (uploadType == 2)
{
if (stream == null || length == 0)
{
throw new Exception("上传类型为流上传时,流和长度不能为空");
}
cloudBlockBlob.UploadFromStreamAsync(stream, length);
}
else if (uploadType == 3)
{
if (by == null)
{
throw new Exception("二进制内容不能为空");
}
cloudBlockBlob.UploadFromByteArrayAsync(by, 0, length);
}
}
/// <summary>
/// 删除blob的文件
/// </summary>
/// <param name="blodPath">blob路径</param>
public static void DeleteBlodFile(string blodPath)
{
var splitArrs = blodPath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
CloudBlobContainer container = blobClient.GetContainerReference(splitArrs[0]);
if (!container.Exists())
{
return;
}
var splitLs = splitArrs.ToList();
splitLs.RemoveAt(0);
var blobpath = string.Join("/", splitLs.ToArray());
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobpath);
if (cloudBlockBlob.Exists())
{
cloudBlockBlob.DeleteAsync();
}
}
/// <summary>
/// 资源url地址
/// </summary>
/// <param name="shareFilePath"></param>
/// <returns></returns>
public static string GetResourceUrlWithSas(string blobFilePath, string sasToken = "")
{
if (string.IsNullOrEmpty(sasToken))
{
var splitArrs = blobFilePath.Split(new string[] { "/", "\\" }, StringSplitOptions.RemoveEmptyEntries);
sasToken = GetAccountSASToken(splitArrs[0]);
}
return filesharebase + blobFilePath + sasToken;
}
/// <summary>
/// 创建sastoken
/// </summary>
/// <param name="storageAccount"></param>
/// <returns></returns>
public static string GetAccountSASToken(string containerName, int expireMonth = 3)
{
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(expireMonth),
Permissions = SharedAccessBlobPermissions.Read
};
// Return the SAS token.
return container.GetSharedAccessSignature(adHocPolicy, null);
}
public static void TestContainer(string localPath)
{
var containerSas = "https://testresource.blob.core.chinacloudapi.cn/testdata?st=2018-08-15T03%3A34%3A45Z&se=2019-08-16T03%3A34%3A00Z&sp=rwdl&sv=2018-03-28&sr=c&sig=zNM0GUOdzuyZAoBV5wuUb28r5OmJPs%2BdStoNAHn4f2c%3D";
CloudBlobContainer container = new CloudBlobContainer(new Uri(containerSas));
CloudBlockBlob blob = container.GetBlockBlobReference("20180815/CN2245689/测试图片.jpg");
blob.UploadFromFile(localPath);
}
public static void TestBlobSas()
{
var containerSas = "https://testresource.blob.core.chinacloudapi.cn/testdata?st=2018-08-15T03%3A34%3A45Z&se=2019-08-16T03%3A34%3A00Z&sp=rwdl&sv=2018-03-28&sr=c&sig=zNM0GUOdzuyZAoBV5wuUb28r5OmJPs%2BdStoNAHn4f2c%3D";
CloudBlobContainer container = new CloudBlobContainer(new Uri(containerSas));
CloudBlockBlob blob = container.GetBlockBlobReference("20180815/CN2245689/测试图片.jpg");
SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(6),
Permissions = SharedAccessBlobPermissions.Read
};
//var str = blob.Uri + blob.GetSharedAccessSignature(adHocPolicy);
var str = blob.Uri + container.GetSharedAccessSignature(adHocPolicy);
}
}