• WCF上传文件


    WCF上传文件:

         在使用WCF通信框架,上传文件时,不能得到上传的结果。经过在百度搜索,终于找到了解决的方法。总结了一下,与大家分享。

         说明:传输模式为流模式,上传文件,并返回上传结果。在Win8、VS2013上测试通过。

    [ServiceContract]
    public interface IService
    {
          // 测试:带消息头:上传文件---返回类型,也是消息类型。
          [OperationContract]
    ImageResponse UploadImages2(ImageData data);

    [OperationContract(AsyncPattern = true)]
    IAsyncResult BeginUploadImages2(ImageData data, AsyncCallback callback, object asyncState);

    //Note: There is no OperationContractAttribute for the end method.
    ImageResponse EndUploadImages2(IAsyncResult result);
    }

    消息契约:


    [MessageContract]
    public class ImageData
    {
    [MessageHeader]
    public string FileName;

    [MessageBodyMember]
    public Stream FileStream;
    }

    [MessageContract]
    public class ImageResponse
    {
    public ImageResponse(bool result)
    {
    this.Result = result;
    }

    [MessageHeader]
    public bool Result;
    }

    接口实现:

    public ImageResponse UploadImages2(ImageData data)
    {
    bool isSuccess = false;

    if (null == data)
    {
    return new ImageResponse(isSuccess);
    }

    string name = data.FileName;
    Stream stream = data.FileStream;

    if (!string.IsNullOrWhiteSpace(name) && stream != null)
    {
    string dir = @"D: emp";
    string savePath = Path.Combine(dir, name);
    isSuccess = FileStreamHelper.SaveFileStream(stream, savePath);
    }

    return new ImageResponse(isSuccess);
    }

    public IAsyncResult BeginUploadImages2(ImageData data, AsyncCallback callback, object asyncState)
    {
    throw new Exception("The method or operation is not implemented.");
    }

    public ImageResponse EndUploadImages2(IAsyncResult result)
    {
    throw new Exception("The method or operation is not implemented.");
    }

    测试代码:

    string filePath = @"D:2.zip";
    string fileName = "2.zip";
    Stream fileStream = FileStreamHelper.GetFileStream(filePath);

    if (fileStream != null)
    {
    Service3Client client = new Service3Client();
    client.UploadImages2Completed += client_UploadImages2Completed;
    client.UploadImages2Async(fileName, fileStream);
    }

    private void client_UploadImages2Completed(object sender, UploadImages2CompletedEventArgs e)
    {
    try
    {
    bool result = e.Result;

    Service3Client client = (Service3Client)sender;
    if (client != null)
    {
    // 释放资源。
    client.Close();
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }
    }

  • 相关阅读:
    leetcode笔记--7 Find the Difference
    数据挖掘:概念与技术--笔记1--度量数据的相似性与相异性
    leetcode笔记--6 Add Digits
    leetcode 笔记5 single number
    数据挖掘导论笔记2 数据集的类型
    **leetcode笔记--4 Sum of Two Integers
    vs2015-Cordova开发安卓应用环境搭建
    c#一些常用的方法集合
    c#根据ip获取城市地址
    asp.net mvc 无刷新加载
  • 原文地址:https://www.cnblogs.com/dblg/p/5190470.html
Copyright © 2020-2023  润新知