使用Lightswitch 2012在Azure Blob存储中保存图像

时间:2013-05-10 16:36:54

标签: azure-storage visual-studio-lightswitch azure-storage-blobs lightswitch-2012

我有一个lightswitch应用程序,它当前存储SQL Azure中的所有数据 - 包括图像。但我想将图像分别保存在Azure Blob存储中,并保留所有非二进制数据。

因此,在lightswitch应用程序中保存实体的结果应如下所示:插入/更新数据SQL Azure并将图像插入/更新到blob存储。

关于问题的最佳方法的任何建议都将非常感激:)。

1 个答案:

答案 0 :(得分:0)

我在LightSwitch应用程序的服务器端添加了一个短代码,用于在添加和更新相关数据条目时将图像保存到Azure Blob。

namespace LightSwitchApplication
{
    public partial class ApplicationDataService
    {
        string storageAccount = [aZURE_STORAGE_NAME_HERE]
        string containerName = [CONTAINTER_NAME_HERE]
        string policyName = [POLICY_NAME_HERE]
        string policySig = [OBTAINED_POLICY_SIG_HERE]

        partial void SaveChanges_Executing()
        {
            if (this.DataWorkspace.ApplicationData.Details.HasChanges)
            {
                EntityChangeSet changeSet = this.DataWorkspace.ApplicationData.Details.GetChanges();
                foreach (IEntityObject entity in changeSet.ModifiedEntities)
                {
                    string type = entity.GetType().Name;
                    // ... 
                    // My type of LightSwitch entities are for example "Places"

                    UploadFileToBlob((Place)entity, containerName, policyName, policySig);
                }
            }
        }

        private void UploadFileToBlob(Place p, String container, String policyName, String policySig)
        {
            string signature = "?sr=c&si=" + policyName + "&sig=" + policySig;
            string file = p.Id + ".png";
            WebResponse resp = UploadFile(storageAccount, container, file, signature, p.Photo);
        }

        static WebResponse UploadFile(string storageAccount, string container, string filename, string signature, byte[] data)
        {
            try
            {
                var req = (HttpWebRequest)WebRequest.Create(string.Format("http://{0}.blob.core.windows.net/{1}/{2}{3}", storageAccount, container, filename, signature));
                req.Method = "PUT";
                req.ContentType = "image/png";
                req.ContentLength = data.Length;
                req.Date = DateTime.UtcNow;
                //req.Headers.Add("x-ms-date", DateTime.UtcNow.ToString());
                req.Headers.Add("x-ms-version", "2012-02-12");
                req.Headers.Add("x-ms-blob-type", "BlockBlob");

                using (Stream stream = req.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var a = req.Headers.ToString();

                return req.GetResponse();
            }
            catch (Exception e)
            { 
                // ...
            }
        }
    }
}

它的作用是在相应的实体发生变化的任何时候将文件发送到blob。方括号中的值需要根据您的Azure帐户进行更改。

获取政策签名的方法是官方文档中描述的共享访问签名:Part 1& Part 2