Windows Azure 系列-- 使用Azure + Web API实现图片上传
来源:互联网 发布:编程app 编辑:程序博客网 时间:2024/04/27 00:34
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可以做到,但是需要服务器端返回js函数的调用代码,有关跨域AJAX请求,具体可以参见这篇不错的文章:
https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/
<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>
1 0
- Windows Azure 系列-- 使用Azure + Web API实现图片上传
- Windows Azure Management API 使用
- Windows Azure入门教学系列 (八):使用Windows Azure Drive
- Windows Azure 系列-- Azure Redis Cache的配置和使用
- Windows Azure 系列-- Azure Queue的操作
- Windows Azure系列-- 配置Azure Power Shell
- 使用Azure customvision api
- Web Sites系列:使用Windows Azure的Web Sites和WebMatrix创建PHP和MySQL站点
- Windows Azure入门教学系列 (七):使用REST API访问Storage Service
- Windows Azure使用必读
- Windows Azure使用体验
- Windows Azure使用必读
- Windows Azure入门教学系列
- Windows Azure入门教学系列 (九):Windows Azure 诊断功能
- Windows Azure入门教学系列 (四):使用Blob Storage
- Windows Azure入门教学系列 (五):使用Queue Storage
- Windows Azure入门教学系列 (六):使用Table Storage
- ISV客户博客系列:Icertis使用Windows Azure处理工作流
- struts2配置文件—struts.xml
- Ubuntu+下构建内核源码树_图文教程
- hbase 概念 + 搭建分布式HA应用
- C++11新特性
- Project Euler:Problem 29 Distinct powers
- Windows Azure 系列-- 使用Azure + Web API实现图片上传
- 资源查找收集整理
- 插入排序
- Installing OpenCms
- 产品经理的核心是啥啊。。
- Project Euler:Problem 30 Digit fifth powers
- Linux 安装Redis全过程日志
- aspose.cells单元格的货币符显示,颜色及赤字显示
- LINUX --- 中断 --- INT 0x13