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:\temp";
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值