码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-06-02 23:27:17      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:

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", "*");


3. web config

 <appSettings>
    
    <add key="AzureImageStorage" value="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="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="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=‘" + d + "‘ width=‘300px‘ height=‘300px‘/>";
}

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

</script>

</html>


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

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/46336505

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!