我正在尝试代码http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx通过 httpwebrequest 执行 POST。
如果我在文本文件中尝试相同的代码,那就没问题了。但是,如果我使用 zip 文件执行此操作,那么当重新下载该文件时,它会说它不是有效的 zip。我认为 zip 部分可能会作为文本而不是二进制上传。然而,该页面确实说“可以在此处包含二进制内容。不要对其进行 Base-64 编码或任何其他内容,只需将其流式传输即可。”但这似乎不适用于给定的代码。我假设我必须更改将文件读取到流的部分:
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 ?不过,我对如何在这种情况下使用它有点困惑,或者这是否是我需要做的。朝着正确的方向推动将是非常棒的。谢谢!
BinaryReader 应该确实可以工作:
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)