2012-12-02 53 views
0

我需要发送一个HttpPostedFileBase到一个wcf服务器来处理在服务器上运行的用户点击“上传文件”按钮后从网页前端处理的内容。我首先在服务合同中使用了HttpPostedFileBase,但它不起作用。然后我尝试将HttpPostedFileBase放入数据合同中,但仍然无法使用。我挣扎了两天来解决这个问题。现在这里是方法:WCF发送HttpPostedFileBase服务进行处理

在服务合同:

[ServiceContract] 
public interface IFileImportWcf 
{ 
    [OperationContract] 
    string FileImport(byte[] file); 
} 

并发现这两种方法,将字节[]以流,反之亦然。

public byte[] StreamToBytes(Stream stream) 
    { 
     byte[] bytes = new byte[stream.Length]; 
     stream.Read(bytes, 0, bytes.Length); 
     stream.Seek(0, SeekOrigin.Begin); 
     return bytes; 
    } 
    public Stream BytesToStream(byte[] bytes) 
    { 
     Stream stream = new MemoryStream(bytes); 
     return stream; 
    } 

在控制器:

[HttpPost] 
public ActionResult Import(HttpPostedFileBase attachment) 
{ 
    //convert HttpPostedFileBase to bytes[] 
    var binReader = new BinaryReader(attachment.InputStream); 
    var file = binReader.ReadBytes(attachment.ContentLength); 
    //call wcf service 
    var wcfClient = new ImportFileWcfClient(); 
    wcfClient.FileImport(file); 
} 

我的问题是:什么是更好的方式来发送HttpPostedFileBase到WCF服务?

回答

1

您需要在这里使用WCF Data Streaming

正如我的理解你的问题,你可以控制你的WCF服务合同。

如果更改合同,类似以下内容:

[ServiceContract] 
public interface IFileImportWcf 
{ 
    [OperationContract] 
    string FileImport(Stream file); 
} 

然后你就可以使用它在客户端:

[HttpPost] 
public ActionResult Import(HttpPostedFileBase attachment) 
{ 
    var wcfClient = new ImportFileWcfClient(); 
    wcfClient.FileImport(attachment.InputStream); 
} 

请注意,您必须启用配置流

<binding name="ExampleBinding" transferMode="Streamed"/> 

(详见上面的链接)

+0

实际上,transferMode应该是“Streamed”,如: – jguo1

+0

嗨,Alex,谢谢你的回答。我会试用。 – jguo1