首页 > 代码库 > Windows Azure 系列-- 使用Azure + Web API实现图片上传

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

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

技术分享

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


[HttpPost]
        public async Task<HttpResponseMessage> 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<string> 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能够做到,可是须要server端返回js函数的调用代码,有关跨域AJAX请求,详细能够參见这篇不错的文章:

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



3. web config

 <appSettings>
    
    <add key="AzureImageStorage" value="http://www.mamicode.com/DefaultEndpointsProtocol=http;AccountName=name;AccountKey=yourkey" />
  </appSettings>
须要注意的地方就是。value中不同意出现空格。这个链接字符串是标准形式,很多其它azure链接字符串,能够參照:

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


4. 推荐下载cloud berry这样的相似FTP的管理工具。方便查看上传的图片,假设传错了能够进行删除:

http://www.cloudberrylab.com


5. 客户端html实现:

<html>

<script src="http://www.mamicode.com/jquery-2.1.1.js"></script>


<form method="post" enctype="multipart/form-data" action="http://localhost:55006/api/values/postfile">

<input type="file" name ="uploadfile" ></input>
<input type="submit" value="http://www.mamicode.com/submit" ></input>




<ul class="imgs">
</ul>

</form>



<script>

$(document).ready(function(){


$.get("http://localhost:55006/api/values/AzureImageUrls", function(data, status){

var html = "";
for(var i = 0;i < data.length; i++){
var d = data[i];
html += "<img src=http://www.mamicode.com/‘" + d + "‘ width=‘300px‘ height=‘300px‘/>";
}

$(".imgs").html(html);
    });
});

</script>

</html>


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