簡體   English   中英

WCF REST 文件上傳

[英]WCF REST File Upload

我正在開發一個 WCF web 服務,該服務需要能夠上傳文件等。

目前我添加“平面圖”項目的方法如下:

[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>

並且 Image 包含一個 base 64 編碼字符串,它代表我通過以下方式轉換為 byte[] 的圖像文件:

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>

您的 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);

我冒昧地將字節數組更改為 Stream,如果圖像很大,您可以選擇流式傳輸(但不需要流式傳輸)

要調用它,您可以使用正確的 Uri(包括類型、令牌和平面圖)創建一個 WebRequest 並執行一個 POST。 將內容類型設置為適合圖像格式(jpeg、png 等)的內容類型,並獲取將圖像復制到其中的請求 stream。 然后在 WebRequest 上調用 GetResponse 以發出 HTTP 請求

您將無法將字節數組作為GET傳遞。 在請求字符串中傳遞這么多數據是行不通的。 你需要做一個 http POST

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM