HttpWebRequest有效。 WebClient.UploadFile没有

时间:2012-05-17 19:48:58

标签: wcf file-upload httpwebrequest webclient

我以为我找到了一种通过使用WebClient.UploadFile而不是HttpWebRequest 来简化我的代码的方法,但我最终在服务器端获得的文件太短了几十个字节损坏。知道bug在哪里吗?

由于

使用HttpWebRequest(工作正常):

       HttpWebRequest req = (HttpWebRequest)HttpWebRequest
                                 .Create("http://" +
                                  ConnectionManager.FileServerAddress + ":" +
                                  ConnectionManager.FileServerPort +
                                  "/binary/up/" + category + "/" +  
                                  Path.GetFileName(filename) + "/" + safehash);

        req.Method = "POST";
        req.ContentType = "binary/octet-stream";
        req.AllowWriteStreamBuffering = false;
        req.ContentLength = bytes.Length;
        Stream reqStream = req.GetRequestStream();

        int offset = 0;
        while (offset < ____)
        {
            reqStream.Write(bytes, offset, _________);
             _______
             _______
             _______

        }
        reqStream.Close();

        try
        {
            HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
        }
        catch (Exception e)
        {
            _____________
        }
        return safehash;

使用WebClient(服务器端的损坏文件):

      var client = new WebClient();
      client.Encoding = Encoding.UTF8;
      client.Headers.Add(HttpRequestHeader.ContentType, "binary/octet-stream");

      client.UploadFile(new Uri("http://" +
              ConnectionManager.FileServerAddress + ":" +
              ConnectionManager.FileServerPort +
              "/binary/up/" + category + "/" +
              Path.GetFileName(filename) + "/" + safehash), filename);

      return safehash;

服务器端是WCF服务:

  [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "up/file/{fileName}/{hash}")]

    void FileUpload(string fileName, string hash, Stream fileStream);

1 个答案:

答案 0 :(得分:5)

WebClient.UploadFile以multipart / form-data格式发送数据。使用HttpWebRequest获取与代码等价的内容是WebClient.UploadData方法:

var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
byte[] fileContents = File.ReadAllBytes(filename);
client.UploadData(new Uri("http://" + ConnectionManager.FileServerAddress + ":" +
       ConnectionManager.FileServerPort +
       "/binary/up/" + category + "/" +
       Path.GetFileName(filename) + "/" + safehash), fileContents);