title: The remote server returned an error: (400) Bad Request - uploading less 2MB file size?
body: <p>The file succeed to upload when it is 2KB or lower in size. The main reason why I use streaming is to be able to upload file up to at least 1 GB. But when I try to upload file with less 1MB size, I get bad request. It is my first time to deal with downloading and uploading process, so I can't easily find the cause of error.  </p>
  
  <p>Testing part:  </p>
  
  <pre><code>private void button24_Click(object sender, EventArgs e)
  {
      try
      {
          OpenFileDialog openfile = new OpenFileDialog();
          if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
          {
              string port = "3445";
              byte[] fileStream;
              using (FileStream fs = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
              {
                  fileStream = new byte[fs.Length];
                  fs.Read(fileStream, 0, (int)fs.Length);
                  fs.Close();
                  fs.Dispose();
              }
  
              string baseAddress = "http://localhost:" + port + "/File/AddStream?fileID=9";
              HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
              request.Method = "POST";
              request.ContentType = "text/plain";
              //request.ContentType = "application/octet-stream";
              Stream serverStream = request.GetRequestStream();
              serverStream.Write(fileStream, 0, fileStream.Length);
              serverStream.Close();
              using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
              {
                  int statusCode = (int)response.StatusCode;
                  StreamReader reader = new StreamReader(response.GetResponseStream());
              }
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message);
      }
  }  
  </code></pre>
  
  <p>Service:  </p>
  
  <pre><code>[WebInvoke(UriTemplate = "AddStream?fileID={fileID}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
  public bool AddStream(long fileID, System.IO.Stream fileStream)
  {
      ClasslLogic.FileComponent svc = new ClasslLogic.FileComponent();
      return svc.AddStream(fileID, fileStream);
  }  
  </code></pre>
  
  <p>Server code for streaming:  </p>
  
  <pre><code>namespace ClasslLogic
  {
      public class StreamObject : IStreamObject
      {
          public bool UploadFile(string filename, Stream fileStream)
          {
              try
              {
                  FileStream fileToupload = new FileStream(filename, FileMode.Create);
                  byte[] bytearray = new byte[10000];
                  int bytesRead, totalBytesRead = 0;
                  do
                  {
                      bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
                      totalBytesRead += bytesRead;
                  } while (bytesRead &gt; 0);
  
                  fileToupload.Write(bytearray, 0, bytearray.Length);
                  fileToupload.Close();
                  fileToupload.Dispose();
              }
              catch (Exception ex) { throw new Exception(ex.Message); }
              return true;
          }
      }
  }  
  </code></pre>
  
  <p>Web config:  </p>
  
  <pre><code>&lt;system.serviceModel&gt;
  &lt;bindings&gt;
    &lt;basicHttpBinding&gt;
      &lt;binding&gt;
        &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2097152" maxBytesPerRead="4096" maxNameTableCharCount="2097152" /&gt;
        &lt;security mode="None" /&gt;
      &lt;/binding&gt;
      &lt;binding name="ClassLogicBasicTransfer" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:15:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="67108864" maxReceivedMessageSize="67108864" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true"&gt;
        &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="67108864" maxBytesPerRead="4096" maxNameTableCharCount="67108864" /&gt;
        &lt;security mode="None"&gt;
          &lt;transport clientCredentialType="None" proxyCredentialType="None" realm="" /&gt;
          &lt;message clientCredentialType="UserName" algorithmSuite="Default" /&gt;
        &lt;/security&gt;
      &lt;/binding&gt;
      &lt;binding name="BaseLogicWSHTTP"&gt;
        &lt;security mode="None" /&gt;
      &lt;/binding&gt;
      &lt;binding name="BaseLogicWSHTTPSec" /&gt;
    &lt;/basicHttpBinding&gt;
  &lt;/bindings&gt;
  &lt;behaviors&gt;
    &lt;serviceBehaviors&gt;
      &lt;behavior&gt;
        &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt;
        &lt;serviceMetadata httpGetEnabled="true" /&gt;
        &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information --&gt;
        &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt;
      &lt;/behavior&gt;
    &lt;/serviceBehaviors&gt;
  &lt;/behaviors&gt;
  &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" /&gt;
  &lt;/system.serviceModel&gt;
  </code></pre>
  
  <p>I'm not sure if this affects the streaming function, because I'm using WCF4.0 rest template 
  which config is dependent in Global.asax.  </p>
  
  <p>One more thing is this, whether I run the service and passing a stream or not, the created file always contain this thing.  </p>
  
  <p><img src="https://i.stack.imgur.com/n2WdX.png" alt="enter image description here"></p>
  
  <p>How could I remove the "NUL" data?  </p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Edit</strong>  </p>
  
  <pre><code>public bool UploadFile(string filename, Stream fileStream)
          {
              try
              {
                  FileStream fileToupload = new FileStream(filename, FileMode.Create);
                  byte[] bytearray = new byte[10000];
                  int bytesRead, totalBytesRead = 0;
                  do
                  {
                      bytesRead = fileStream.Read(bytearray, totalBytesRead, bytearray.Length - totalBytesRead);
                      totalBytesRead += bytesRead;
  
                  } while (bytesRead &gt; 0);
  
                  fileToupload.Write(bytearray, 0, totalBytesRead);
                  fileToupload.Close();
                  fileToupload.Dispose();
              }
              catch (Exception ex) { throw new Exception(ex.Message); }
              return true;
          }
  </code></pre>