Azure图片资源访问

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;


string strConnect = "AZURE的KEY";
string blobFileUrl = "IMG的URL";

blobFileUrl = HttpUtility.UrlDecode(blobFileUrl);
try
{
    // To create the account SAS, you need to use your shared key credentials. Modify for your account. 
    //var strConnect = "";
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(strConnect);
    // Create a new access policy for the account.
    SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
    {
        Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
        Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
        ResourceTypes = SharedAccessAccountResourceTypes.Service,
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
        Protocols = SharedAccessProtocol.HttpsOnly
    };

    // Return the SAS token.
    var sasToken = storageAccount.GetSharedAccessSignature(policy);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    // Create new storage credentials using the SAS token.
    StorageCredentials accountSAS = new StorageCredentials(sasToken);
    // Use these credentials and the account name to create a Blob service client. 
    // The permissions granted by the account SAS also permit you to retrieve service properties. 
    CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobFileUrl), blobClient);
    //blob.DownloadToFile(downPath + "\\" + blob.Name, System.IO.FileMode.Create);
    using (MemoryStream msRead = new MemoryStream())
    {
        var fileName = blob.Name;
        blob.DownloadToStream(msRead);
        byte[] bytesInStream = msRead.ToArray();

        //解析图片=》
        Response.Clear();
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        string[] imgExtensions = new string[] { ".jpg", ".gif", ".png", ".bmp", ".jpeg" };
        var extension = Path.GetExtension(fileName).ToLower();
        if (imgExtensions.Contains(extension))
        {
            Response.ContentType = "image/jpeg";
        }
        else
        {
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
            Response.ContentType = "application/octet-stream";
        }
        Response.BinaryWrite(bytesInStream);
        Response.Flush();
        Response.End();
    }
}
catch (Exception ex)
{

}

  

//需要引用 Microsoft.WindowsAzure.Configuration.dll
//需要引用 Microsoft.WindowsAzure.Storage.dll

  

posted @ 2021-03-23 15:52  全栈攻城师  阅读(81)  评论(0)    收藏  举报