5

我正在尝试将文件分块发送到 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);
    }
4

2 回答 2

2

我怀疑您将其上传为表单编码可能会令人困惑。但这不是您要发送的内容(除非您在掩饰某些东西)。MIME 类型真的正确吗?

数据有多大?你需要分块上传吗?一些服务器可能不喜欢在单个请求中这样做;我很想通过WebClient.UploadData.

于 2009-11-06T10:02:28.707 回答
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 我希望这会有所帮助

于 2011-03-05T12:15:35.677 回答