在C#中使用POST/httpwebrequest上传zip文件 [英] Uploading zip file with POST/httpwebrequest in C#

查看:1343
本文介绍了在C#中使用POST/httpwebrequest上传zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试

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.

如果我在文本文件中尝试使用相同的代码,也可以.但是,如果我使用一个zip文件,那么当重新下载该文件时,它表示它不是有效的zip.我认为zip部分可能会以文本而不是二进制的形式上传.但是,该页面确实说:可以在此处包括二进制内容.不要对它进行base-64编码或其他任何编码,只需对其进行流式处理即可."但这似乎不适用于给定的代码.我假设我必须将读取文件的部分更改为流:

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

也许要使用BinaryReader?我对于如何在这种情况下使用它还是感到困惑,或者这甚至是我需要做的.向正确的方向轻推会很棒.谢谢!

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!

推荐答案

BinaryReader应该确实可以工作:

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

这篇关于在C#中使用POST/httpwebrequest上传zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆