2011-07-12 101 views
3

我正在開發一個WCF Web服務,它需要能夠上傳其他文件。WCF REST文件上傳

目前我添加一個「佈局規劃」項目的方法是這樣的:

[OperationContract] 
[WebInvoke(Method = "GET", 
    ResponseFormat = WebMessageFormat.Xml, 
    BodyStyle = WebMessageBodyStyle.Wrapped, 
    UriTemplate = "Floorplan?token={token}&floorplan={floorplan}")] 
string XmlInputFloorplan(string token, string floorplan); 

我需要改變它,這樣圖像會被上傳,因爲這調用可以像一個方法使用的一部分:

public static Guid AddFile(byte[] stream, string type); 

在這種情況下byte[]是圖像的內容。然後將得到的guid傳遞到數據層,並且完成平面佈局的添加。

所以我需要弄清楚兩件事情:

1)我應該如何改變XmlInputFloorplan接口方法,以便它也允許圖像作爲參數?
2)如何在更改後使用服務?

謝謝!

這是我如何解決它:

[OperationContract] 
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Xml, 
    BodyStyle = WebMessageBodyStyle.Wrapped, 
    UriTemplate = "Floorplan")] 
XmlDocument XmlInputFloorplan(Stream content); 

期待一個輸入XML等:

<?xml version="1.0" encoding="us-ascii" ?> 
<CreateFloorplanRequest> 
    <Token></Token> 
    <Floorplan></Floorplan> 
    <Image></Image> 
</CreateFloorplanRequest> 

和圖像包含表示我轉換爲字節的圖像文件的基64編碼的串[]通過:

XmlDocument doc = new XmlDocument(); 
doc.Load(content); 
content.Close(); 

XmlElement body = doc.DocumentElement; 
byte[] imageBytes = Convert.FromBase64String(body.ChildNodes[2].InnerText); 

爲了讓這個我不得不像這樣配置Web.config:

<service behaviorConfiguration="someBehavior" name="blah.blahblah"> 
    <endpoint 
     address="DataEntry" 
     behaviorConfiguration="web" 
     binding="webHttpBinding" 
     bindingConfiguration="basicBinding" 
     contract="blah.IDataEntry" /> 
</service> 

<bindings> 
    <webHttpBinding> 
    <binding name="basicBinding" maxReceivedMessageSize ="50000000" 
     maxBufferPoolSize="50000000" > 
     <readerQuotas maxDepth="500000000" 
     maxArrayLength="500000000" maxBytesPerRead="500000000" 
     maxNameTableCharCount="500000000" maxStringContentLength="500000000"/> 
     <security mode="None"/> 
    </binding> 
    </webHttpBinding> 
</bindings> 

回答

4

你的URI會完全不同 - 這樣的事情(我不得不作出一些猜測)

[OperationContract] 
[WebInvoke(Method = "POST", 
      ResponseFormat = WebMessageFormat.Xml, 
      BodyStyle = WebMessageBodyStyle.Wrapped, 
      UriTemplate = "Floorplan?type={type}&token={token}&floorplan={floorplan}")] 
Guid XmlInputFloorplan(string type, string token, string floorplan, Stream image); 

我已經採取了改變字節數組的流賦予的自由你可以選擇流式傳輸圖像(但不需要流式傳輸)

要調用此選項,您可以使用正確的Uri(包括類型,標記和平面佈局圖)創建WebRequest並執行POST。將內容類型設置爲圖像格式(jpeg,png等)的正確內容並獲取將圖像複製到其中的請求流。然後調用WebRequest上的GetResponse以發出HTTP請求

+0

這是行不通的。它向我大吼,它不知道如何處理'Stream'參數。 – FlyingStreudel

+0

什麼叫你在哪裏? –

+0

這是說,對於一篇文章,它只需要一個參數調用流。我最終刪除了所有參數,只是在流中發送一個xml文件。我仍然接受這個答案,因爲它讓我走上了正確的道路。 – FlyingStreudel

2

您將無法將字節數組作爲GET傳遞。將請求字符串中的大量數據傳遞給工作。你將需要做一個http POST