HttpWebRequest works. WebClient.UploadFile doesn't

青春壹個敷衍的年華 提交于 2019-12-19 11:18:14

问题


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


来源:https://stackoverflow.com/questions/10642536/httpwebrequest-works-webclient-uploadfile-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!