具有可选文件上载的REST发布请求

时间:2013-05-09 15:51:08

标签: c# wcf

在创建WCF REST服务时,我在json中接收数据并能够保存在数据库中。现在我需要选择上传文件(可选,图像或视频)与相同的服务。我尝试发送字节数组,但它可能因为序列化这么长的数组而给出错误的请求错误。我读到要上传大文件我需要使用流。发送其他参数时我该怎么做?我正在创建此服务以从移动设备接收数据。这是我的服务界面

[WebInvoke(UriTemplate = "SaveFBPost", 
    Method = "POST", 
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void SaveFacebookPost(FBPostData fbPostData);

公共类FBPostData:

[DataMember]
public string scheduleDate { get; set; }

[DataMember]
public string userId { get; set; }

[DataMember]
public string groupId { get; set; } 

[DataMember]
public string postText { get; set; }

[DataMember]
public byte[] file { get; set; }

[DataMember]
public string fileType { get; set; }

[DataMember]
public string accessToken { get; set; }

2 个答案:

答案 0 :(得分:1)

我首先要为web.config中的特定绑定增加maxBufferSize和maxArrayLength,看看是否能解决问题。

您应该能够提供有关错误的更多详细信息,这样您就可以确切了解为什么会收到400错误。

This blog article过去对我也很有用 - 底部也有一些很好的链接。

另请查看Stream课程。不确定“发送其他参数”是什么意思 - 如果你能澄清这一点,我们可以给你更多指导。

答案 1 :(得分:1)

我不得不使用来自android和multipart解析器的multipart上传来解决这个问题。我使用Apache mime库上传文件并发送如下参数:

HttpPost postRequest = new HttpPost(
                context.getString(R.string.url_service_fbpost));
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        if(postData.data != null && !"".equals(postData.fileName)){
            ByteArrayBody bab = new ByteArrayBody(postData.data, postData.fileName);
            reqEntity.addPart("uploaded", bab);
        }
        reqEntity.addPart("scheduleDate", new StringBody(postData.scheduleDate));
        reqEntity.addPart("userId", new StringBody(postData.userId));
        reqEntity.addPart("groupIds",
                new StringBody(postData.groupIds.toString()));
        reqEntity.addPart("postText", new StringBody(postData.postText));
        reqEntity.addPart("postType", new StringBody(postData.postType));
        reqEntity.addPart("accessToken", new StringBody(postData.accessToken));
        if(postData.postId != null && postData.postId.length() > 0) {
            reqEntity.addPart("postId", new StringBody(postData.postId));
        }
        postRequest.setEntity(reqEntity);

之后我使用c#multipart解析器来获取文件和参数。这是服务代码:

[OperationContract]
[WebInvoke(Method = "POST",
        UriTemplate = "UploadFBPost",
        BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void UploadFBPost(Stream stream);

 public void UploadFBPost(Stream stream)
{
    MultipartParser parser = new MultipartParser(stream);

    // Saves post data in database
    if (parser.Success)
    {
        string fileName = null, userId = null, postText = null, postType = null, accessToken = null;
        DateTime scheduleDate = DateTime.Now;
        string[] groupIds = null;
        int postId = 0;

        // Other contents
        foreach (MyContent content in parser.MyContents)
        {
            switch (content.PropertyName)
            {
                case "scheduleDate":
                    if (string.IsNullOrEmpty(content.StringData.Trim()))
                        scheduleDate = DateTime.Now;
                    else
                        scheduleDate = DateTime.ParseExact(content.StringData.Trim(), "M-d-yyyy H:m:s", CultureInfo.InvariantCulture);
                    break;

                case "fileName":
                    fileName = content.StringData.Trim();
                    break;

                case "userId":
                    userId = content.StringData.Trim();
                    break;

                case "postText":
                    postText = content.StringData.Trim();
                    break;

                case "accessToken":
                    accessToken = content.StringData.Trim();
                    break;

                case "groupIds":
                    groupIds = content.StringData.Trim().Split(new char[] { ',' });
                    break;

                case "postType":
                    postType = content.StringData.Trim();
                    break;

                case "postId":
                    postId = Convert.ToInt32(content.StringData.Trim());
                    break;
            }
        }

        string videoFile = null, imageFile = null;
        if (parser.FileContents != null)
        {
            string filePath = GetUniqueUploadFileName(parser.Filename);
            File.WriteAllBytes(filePath, parser.FileContents);
            if (postType == "photo")
                imageFile = Path.GetFileName(filePath); 
            else 
                videoFile = Path.GetFileName(filePath); 
        }
    }
}

您需要根据要发送的数据修改多部分解析器。希望这会节省很少的时间。

感谢雷的帮助。

还有一件事。我不得不在网络配置中添加这些行:

<httpRuntime maxRequestLength="2000000"/>

<bindings>
  <webHttpBinding>
    <binding maxBufferSize="65536"
             maxReceivedMessageSize="2000000000"
             transferMode="Streamed">
    </binding>
  </webHttpBinding>
</bindings>