我正在尝试将块中的文件发送到HttpHandler但是当我在HttpContext中收到请求时,inputStream为空。
所以a:发送时我不确定我的HttpWebRequest是否有效 和b:接收时我不知道如何在HttpContext中检索流
任何帮助都非常感谢!
这是我如何通过客户端代码提出请求:
private void Post(byte[] bytes)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2977/Upload");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.SendChunked = true;
req.Timeout = 400000;
req.ContentLength = bytes.Length;
req.KeepAlive = true;
using (Stream s = req.GetRequestStream())
{
s.Write(bytes, 0, bytes.Length);
s.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
}
这就是我在HttpHandler中处理请求的方式:
public void ProcessRequest(HttpContext context)
{
Stream chunk = context.Request.InputStream; //it's empty!
FileStream output = new FileStream("C:\\Temp\\myTempFile.tmp", FileMode.Append);
//simple method to append each chunk to the temp file
CopyStream(chunk, output);
}
答案 0 :(得分:2)
我怀疑您将其上传为表单编码可能会令人困惑。但这不是你发送的东西(除非你在掩饰某些东西)。这种MIME类型是否真的正确?
数据有多大?你需要分块上传吗?有些服务器在单个请求中可能不喜欢这样;我很想通过WebClient.UploadData
使用多个简单的请求。
答案 1 :(得分:0)
我正在尝试相同的想法,并成功通过Post httpwebrequest发送文件。请参阅以下代码示例
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = @"fileName=" + fileName +
"&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}
我已经写过博客,你在这里看到了整个HttpHandler / HttpWebRequest帖子 http://aspilham.blogspot.com/2011/03/file-uploading-in-chunks-using.html 我希望这会有所帮助