2012-12-02 56 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