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);
}
}

原文地址:https://www.cnblogs.com/dblg/p/5190470.html