HttpWebRequest works. WebClient.UploadFile doesn&#

2019-06-03 16:35发布

问题:

I thought I figured out a way to simplify my code by using WebClient.UploadFile instead of HttpWebRequest, but I end up getting a file on the server end that is a few dozen bytes too short and corrupted. Any idea where the bug lies?

Thanks

Using HttpWebRequest (works fine):

       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;

Using WebClient (corrupt file on server end):

      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;

Server side is a WCF service:

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

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

回答1:

WebClient.UploadFile sends the data in a multipart/form-data format. What you want to use to have the equivalent to the code using HttpWebRequest is the WebClient.UploadData method:

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