您的位置:首页 > 编程语言

[SDK2.2]Windows Azure Storage (16) 使用WCF服务,将本地图片上传至Azure Storage (上) 客户端代码

2013-11-01 13:47 901 查看
  Windows Azure Platform 系列文章目录

  前一章我们完成了服务器端的代码,并且已经发布到了Windows Azure云端。

  本章我们将实现客户端的代码,客户端这里我们使用的是Windows Form。

  源代码下载

  1.我们用管理员身份,运行VS2013

  2.新建项目类型为Windows Form Application,并将项目名称修改为LeiAzureClient

  3.本章需要使用HttpClient类来调用WCF,需要进行相关的配置:

  点击Project LeiAzureClient,右键,选择Manage NuGet Packages。如下图

  


  4.在弹出的窗口里,查询"Microsoft HTTP Client Libraries",查询完毕后,点击Install



  5.安装完毕后,我们回到项目文件的Form1,在窗口里增加一个按钮,并设置Text为UploadPic

  


  6.在Form1.cs的引用内容如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;


  7.增加如下代码:

     string urlPrefix = "http://leiazureservice.cloudapp.net/service1.svc";
private void button1_Click(object sender, EventArgs e)
{
string uriString = urlPrefix + @"/UploadPic";

using (HttpClient client = new HttpClient())
{
//Please copy file to C:\
var fs = new FileStream(@"c:\\WP7.jpg", FileMode.Open, FileAccess.Read);

var ms = new MemoryStream();
fs.CopyTo(ms);

ByteArrayContent arrayContent = new ByteArrayContent(ms.ToArray());
arrayContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var response = client.PostAsync(new Uri(uriString, UriKind.Absolute), arrayContent).Result;

//lblResult.Text = resp.ToString();
if (response.IsSuccessStatusCode)
{
//will return Uploaded GUID
string picName = response.Content.ReadAsStringAsync().Result.ToString();

//Please check the Upload Photos URL AT
//http://leiwcfstorage.blob.core.windows.net/photos/{GUID}.jpg
//e.g. http://leiwcfstorage.blob.core.windows.net/photos/39c51e48-e758-8697-d402-8df45f071d40.jpg }

}
}


  在上面的代码中,我们实现以下功能:

  1)指定Azure WCF URL

  2)将本地已经存在的C:\WP7.jpg文件上传至Azure Storage

  3)如果服务器端的response.IsSuccessStatusCode返回True,则调用WCF成功

  4)response.Content.ReadAsStringAsync().Result.ToString();将会返回服务器端的结果

  

  8.我们执行Windows Form工程,点击UploadPic按钮,查看response.IsSuccessStatusCode返回结果

  如果返回结果为Ture,我们打开IE浏览器,查看到leiwcfstorage里新建了名为photosContainer

  


  9.点击上图photos,我们可以查看到上传成功的图片。如下图:

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: