使用WCF REST上传文件

时间:2011-04-25 19:42:14

标签: .net wcf rest file-upload

我正在使用以下代码:

    static void test()
        {
            string address = "http://localhost:4700/HostDevServer/HelloWorldService.svc";
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
            req.Method = "POST";
            req.ContentType = "text/xml;charset=UTF-8";
            Stream reqStream = req.GetRequestStream();
            string fileContents = "the quick brown fox jumped over the lazy dog.";
            byte[] bodyContents = Encoding.UTF8.GetBytes(fileContents);
            reqStream.Write(bodyContents, 0, bodyContents.Length);
            reqStream.Close();

            HttpWebResponse resp;
            try
            {
                **resp = (HttpWebResponse)req.GetResponse();**
            }
            catch (WebException e)
            {
                resp = (HttpWebResponse)e.Response;
            }
            Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); 
        }



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyWCFServices
{
    public class HelloWorldService : IHelloWorldService
    {
        public String GetMessage(String name)
        {
            return "Hello world from " + name + "!";
        }

        public bool UploadFile(Stream fileContent)
        {
            using (StreamReader fileContentReader = new StreamReader(fileContent))
            {
                string content = fileContentReader.ReadToEnd();
                File.WriteAllText(Path.Combine(@"c:\temp\aa.tmp"), content);
            }
            return false;
        }  
    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.IO;
using System.Web;

namespace MyWCFServices
{
    [ServiceContract]
    interface IHelloWorldService
    {
        [OperationContract]
        String GetMessage(String name);

        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "File/{fileName}")]
        //[WebContentType("application/octet-stream")]
        bool UploadFile(Stream fileContents); 

        //[OperationContract]
        //[WebInvoke(UriTemplate = "UploadFile/{fileName}")]
        //void UploadFile(string fileName, Stream fileContent); 
    }
}

在上传文件时,我在粗体突出显示的代码中收到了Unsopported媒体类型错误。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

虽然我无法直接看到它会影响这个特定示例的原因 - 您不应该将文件的字节写入Web请求,因为可能存在不期望或不支持的字节值。

您应该使用

将文件的字节编码为base 64
Convert.ToBase64String

有效地将文件上传为字符串。

然后在另一端将值视为服务方法的字符串参数,并使用

Convert.FromBase64String

要获取字节,然后再次拥有原始文件。在我的公司,我们使用Web服务来获取docx之类的二进制文件,这就是我们的工作方式 - 它可以为您提供服务。