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

简介:

Windows Azure Platform 系列文章目录

 

  这几天工作上的内容,把项目文件和源代码拿出来给大家分享下。

  源代码下载:Part1    Part2    Part3

 

  我们在写WEB服务的时候,经常需要把本地的文件上传至服务器端进行保存,类似于上传附件的功能。

  在本章中,我们将新建WCF服务并上传至Azure云端,实现把本地的图片通过WCF保存至Azure Storage。

  本章需要掌握的技术点:

  1.WCF服务

  2.Azure Storage

  本章将首先介绍服务器端程序代码。

 

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

  2.新建Windows Azure Cloud Project,并命名为LeiAzureService

  

  3.添加"WCF Service Web Role",并重命名为LeiWCFService。

  

  4.打开IE浏览器,登录http://manage.windowsazure.com,在Storage栏,新建storage name为leiwcfstorage

  

 

 

  5.我们回到VS2013,选择Project LeiAzureService,展开Roles->LeiWCFService,右键属性

  

   6.在弹出的窗口里,Configuration栏,将Instance count设置成2, VM Size选择Small

  

  这样,就同时有2台 small size(1core/1.75GB)的Cloud Service自动做负载均衡了。

 

  7.在Settings栏,选择Add Setting,设置Name为StorageConnectionString,Type选择Connection String,然后点击Value栏的按钮

  在Create Storage Connection String中,选择Account Name为我们在步骤4中创建的leiwcfstorage

  

 

  8.再次点击Add Setting,设置Name为ContainerName,Type选择String,Value设置为photos。切记Value的值必须是小写

  

 

  9.在Project LeiWCFService中,修改IService1.cs

复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace LeiWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/UploadPic", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string UploadPic(Stream ImageStream);
       
    }
}
复制代码

  

  10.修改Service1.svc

  这个类的主要功能是读取Azure配置文件cscfg的节点信息,并根据storage connection string,创建Container,并将本地的图片文件名重命名为GUID,并保存至Container

  项目中需要添加相关的引用,笔者就不详述了。

复制代码
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;


namespace LeiWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public string UploadPic(Stream ImageStream)
        {
            try
            {
                //获取ServiceConfiguration.cscfg配置文件的信息
                var account = CloudStorageAccount.Parse(
                    CloudConfigurationManager.GetSetting("StorageConnectionString"));

                var client = account.CreateCloudBlobClient();

                //获得BlobContainer对象
                CloudBlobContainer blobContainer
                    = client.GetContainerReference(CloudConfigurationManager.GetSetting("ContainerName"));

                if (!blobContainer.Exists())
                {
                    // 检查container是否被创建,如果没有,创建container

                    blobContainer.CreateIfNotExists();
                    var permissions = blobContainer.GetPermissions();

                    //对Storage的访问权限是可以浏览Container
                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                    blobContainer.SetPermissions(permissions);
                }


                Guid guid = Guid.NewGuid();
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference(guid.ToString() + ".jpg");
                blob.Properties.ContentType = "image/jpeg";
                //request.Content.Headers.ContentType.MediaType

                //blob.UploadFromByteArray(content, 0, content.Length);
                blob.UploadFromStream(ImageStream);
                blob.SetProperties();

                return guid.ToString();
            }
            catch (Exception ex)
            {
                return ex.InnerException.ToString();
            }
        }
    }
}
复制代码

   以上代码和配置,实现了以下功能点:

  1.在Windows Azure Storage里创建名为photos的Container,并且设置Storage的访问权限

  2.设置上传的BlockbName为GUID

  3.通过UploadFromStream,将客户端POST的Stream保存到Azure Storage里

 

  11.修改Web.config的 <system.serviceModel>节点。设置WCF的相关配置。

复制代码
  <system.serviceModel>
    <bindings>
      <!--<webHttpBinding></webHttpBinding>-->
      <webHttpBinding>
        <binding name="WCFServiceBinding"
                 maxReceivedMessageSize="10485760"
                 maxBufferSize="10485760"
                 closeTimeout="00:01:00" openTimeout="00:01:00"
                 receiveTimeout="00:10:00" sendTimeout="00:01:00">
          <security mode="None"/>
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="LeiWCFService.Service1" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" contract="LeiWCFService.IService1"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
复制代码

  

  

  12.在VS2013离,点击Save All,并将项目发布至Windows Azure。

  DNS我们设置为LeiAzureService

  13.等待项目发布结束后,在IE浏览器中输入http://leiazureservice.cloudapp.net/service1.svc/help看到如下的图片,就证明发布成功了

  

    

 

分类:  Azure Storage

本文转自Lei Zhang的博客博客园博客,原文链接:http://www.cnblogs.com/threestone/p/3398818.html,如需转载请自行联系原作者
目录
相关文章
|
4月前
|
存储 人工智能 开发工具
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
只需要通过向AI助理提问的方式输入您的需求,即可瞬间获得核心流程代码及参数,缩短学习路径、提升开发效率。
1493 4
AI助理化繁为简,速取代码参数——使用python SDK 处理OSS存储的图片
|
3天前
|
API 开发工具 Python
【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
本文介绍如何使用Python SDK为中国区微软云(China Azure)中的虚拟机磁盘创建快照。通过Azure Python SDK的Snapshot Class,指定`location`和`creation_data`参数,使用`Copy`选项从现有磁盘创建快照。代码示例展示了如何配置Default Azure Credential,并设置特定于中国区Azure的`base_url`和`credential_scopes`。参考资料包括官方文档和相关API说明。
|
16天前
|
机器学习/深度学习 人工智能 开发者
DeepSeek服务器繁忙?拒绝稍后再试!基于阿里云PAI实现0代码一键部署DeepSeek-V3和DeepSeek-R1大模型
阿里云PAI平台支持零代码一键部署DeepSeek-V3和DeepSeek-R1大模型,用户可轻松实现从训练到部署再到推理的全流程。通过PAI Model Gallery,开发者只需简单几步即可完成模型部署,享受高效便捷的AI开发体验。具体步骤包括开通PAI服务、进入控制台选择模型、一键部署并获取调用信息。整个过程无需编写代码,极大简化了模型应用的门槛。
197 7
|
4月前
|
Python
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
使用Python的socket库实现客户端到服务器端的图片传输,包括客户端和服务器端的代码实现,以及传输结果的展示。
225 3
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
|
4月前
|
IDE 网络安全 开发工具
IDE之vscode:连接远程服务器代码(亲测OK),与pycharm链接服务器做对比(亲自使用过了),打开文件夹后切换文件夹。
本文介绍了如何使用VS Code通过Remote-SSH插件连接远程服务器进行代码开发,并与PyCharm进行了对比。作者认为VS Code在连接和配置多个服务器时更为简单,推荐使用VS Code。文章详细说明了VS Code的安装、远程插件安装、SSH配置文件编写、服务器连接以及如何在连接后切换文件夹。此外,还提供了使用密钥进行免密登录的方法和解决权限问题的步骤。
2079 0
IDE之vscode:连接远程服务器代码(亲测OK),与pycharm链接服务器做对比(亲自使用过了),打开文件夹后切换文件夹。
|
4月前
|
IDE 网络安全 开发工具
IDE之pycharm:专业版本连接远程服务器代码,并配置远程python环境解释器(亲测OK)。
本文介绍了如何在PyCharm专业版中连接远程服务器并配置远程Python环境解释器,以便在服务器上运行代码。
793 0
IDE之pycharm:专业版本连接远程服务器代码,并配置远程python环境解释器(亲测OK)。
|
4月前
|
Linux C语言 C++
vsCode远程执行c和c++代码并操控linux服务器完整教程
这篇文章提供了一个完整的教程,介绍如何在Visual Studio Code中配置和使用插件来远程执行C和C++代码,并操控Linux服务器,包括安装VSCode、安装插件、配置插件、配置编译工具、升级glibc和编写代码进行调试的步骤。
658 0
vsCode远程执行c和c++代码并操控linux服务器完整教程
|
4月前
|
前端开发 Java
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
文章介绍了如何使用SpringBoot创建简单的后端服务器来处理HTTP请求,包括建立连接、编写Controller处理请求,并返回响应给前端或网址。
83 0
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
|
5月前
|
设计模式 数据库连接 PHP
PHP中的设计模式:如何提高代码的可维护性与扩展性在软件开发领域,PHP 是一种广泛使用的服务器端脚本语言。随着项目规模的扩大和复杂性的增加,保持代码的可维护性和可扩展性变得越来越重要。本文将探讨 PHP 中的设计模式,并通过实例展示如何应用这些模式来提高代码质量。
设计模式是经过验证的解决软件设计问题的方法。它们不是具体的代码,而是一种编码和设计经验的总结。在PHP开发中,合理地使用设计模式可以显著提高代码的可维护性、复用性和扩展性。本文将介绍几种常见的设计模式,包括单例模式、工厂模式和观察者模式,并通过具体的例子展示如何在PHP项目中应用这些模式。
|
5月前
|
网络安全 开发工具 云计算
服务器看代码阿里云
随着云计算技术的发展,阿里云作为国内领先的云计算服务提供商,其服务器受到广大用户青睐。本文主要介绍如何在阿里云服务器上便捷地查看与管理代码,如使用SSH连接服务器并通过命令行工具打开文件,以及利用Git进行版本控制和协作开发,提高代码管理效率。无论个人开发者还是企业团队,都能借助阿里云服务器高效地部署与管理应用程序,提升工作效率及产品质量。
101 10