Uploading zip file with POST/httpwebrequest in C#

2019-02-28 07:21发布

问题:

I'm trying code from http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx to do a POST through httpwebrequest.

If I try this same code with a text file, it's fine. However if I do it with a zip file, then when re-download that file it's saying it's not a valid zip. I assume the zip portion is likely getting uploaded as text rather than binary. However, that page does say " It's OK to include binary content here. Don't base-64 encode it or anything, just stream it on in." But this doesn't seem to be working with the given code. I'm assuming I have to change the portion that reads the file to the stream:

  using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
  {
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
      stream.Write(buffer, 0, bytesRead);
    }
    fileStream.Close();
  }

Maybe to use BinaryReader? I'm a bit confused on how to use that in this context though, or if it's even what I need to do. A nudge in the right direction would be awesome. Thanks!

回答1:

BinaryReader should work indeed:

FileInfo fInfo = new FileInfo(file.FullName);
// 
long numBytes = fInfo.Length;

FileStream fStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fStream);

byte[] bdata = br.ReadBytes((int)numBytes);

br.Close();

fStream.Close();

// Write bdata to the HttpStream
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("url-here");
// Additional webRequest parameters settings.
HttpStream stream = (Stream)webRequest.GetRequestStream();
stream .Write(bdata, 0, bdata.Length);
stream.Close();

HttpWebResponse response = (HttpWebRewponse)webRequest.GetResponse();