WCF REST文件上传

3

我正在开发一个需要上传文件的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>

图片包含一个表示图像文件的base64编码字符串,我通过以下方式将其转换为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>
2个回答

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

我已经自作主张将byte数组更改为流(Stream),这样如果图像很大,您就可以选择进行流式传输(但不需要进行流式传输)。
要调用此函数,您可以创建带有正确Uri(包括类型、令牌和楼层平面图)的WebRequest并执行POST。将内容类型设置为图像格式(jpeg、png等),并获取请求流将图像复制到其中。然后调用WebRequest上的GetResponse以发出HTTP请求。

这个不行。它告诉我它不知道如何处理 Stream 参数。 - FlyingStreudel
它说对于一个帖子,它期望恰好一个参数调用流。最终我删除了所有的参数,只是在流中发送了一个xml文件。虽然这让我走上了正确的道路,但我仍然接受这个答案。 - FlyingStreudel
我肯定在.NET 4下做过这个 - 你在用哪个版本的.NET? - Richard Blewett
@RichardBlewett 这样行不通。我也有同样的问题。流参数不允许附加任何其他参数。我们必须找到其他解决方案。 - Faizan Mubasher

2

您无法将字节数组作为GET传递。在请求字符串中传递这么多数据是行不通的。您需要进行HTTP POST


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接