Windows Azure 系列-- 使用Azure + Web API实现图片上传

1. 创建1个Azure账号,登录之后创建1个AzureStorage,左下方点Manage Access会看到Primary Access Key和Storage Account,记住它们的位置,等下需要配置到Web.config中。

Windows Azure 系列-- 使用Azure + Web API实现图片上传_第1张图片

2. 创建Web.Api project,上传图片的代码:


[HttpPost]
        public async Task PostFile()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = await request.Content.ReadAsMultipartAsync(provider);




            string accountName = "your account stro";
            string accountKey = "your key";
            var creds = new StorageCredentials(accountName, accountKey);
            var account = new CloudStorageAccount(creds, useHttps: true);

            CloudBlobClient client = account.CreateCloudBlobClient();

            CloudBlobContainer sampleContainer = client.GetContainerReference("samples");
            sampleContainer.CreateIfNotExists();
            sampleContainer.SetPermissions(new BlobContainerPermissions()
            {
               PublicAccess = BlobContainerPublicAccessType.Blob
            });





            foreach (MultipartFileData file in provider.FileData)
            {
                var name = file.Headers.ContentDisposition.FileName.Replace("\"","");
                
                CloudBlockBlob blob = sampleContainer.GetBlockBlobReference(name);
                using (var filestream = File.OpenRead(file.LocalFileName))
                {
                    blob.UploadFromStream(filestream);
                }
            }
            return Request.CreateResponse(HttpStatusCode.OK);

        }

        [HttpGet]
        public IEnumerable AzureImageUrls()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            var connStr = ConfigurationManager.AppSettings["AzureImageStorage"];
            var accnt = CloudStorageAccount.Parse(connStr);
            var client = accnt.CreateCloudBlobClient();
            var blobs = client.GetContainerReference("samples" /*container name*/).ListBlobs();

            var urls = blobs.Select(blob => blob.Uri.AbsoluteUri).ToList();
            return urls;
        }

包含了两个Action,PostFile和AzureImageUrls,前者用来接收post过来的文件对象,后者用于从Azure中获取uri返回到客户端。

首先,在上传时,需要设置这行代码:

PublicAccess = BlobContainerPublicAccessType.Blob

如果不设置的话,默认的访问权限是不可以在客户端直接访问Blob图片的,因而显示不出图片。


其次,在客户端获取URI时,API中需要设置这行代码:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

因为跨域做AJAX默认是不允许的,这行代码的实现方式为CORS(Cross Origin Resource sharing),另外还有JSONP可以做到,但是需要服务器端返回js函数的调用代码,有关跨域AJAX请求,具体可以参见这篇不错的文章:

https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/



3. web config

 
    
    
  
需要注意的地方就是,value中不允许出现空格。这个链接字符串是标准形式,更多azure链接字符串,可以参照:

https://www.connectionstrings.com/windows-azure/


4. 推荐下载cloud berry这种类似FTP的管理工具,方便查看上传的图片,如果传错了可以进行删除:

http://www.cloudberrylab.com


5. 客户端html实现:








你可能感兴趣的:(Microsoft,Azure)