在C#.Net中使用HttpWebRequest异步上传大文件 [英] Asynchronous Upload of Large File Using HttpWebRequest in C#.Net

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

问题描述

我想使用HttpWebRequest以异步方式上传大文件.

I want to upload a large file in asynchronous way using HttpWebRequest.

说我使用HttpWebRequest&在接收端,它应该获得流&播放音频文件.

Say i upload a audio file from using HttpWebRequest & on the receiver end it should get the stream & play the audio file.

参考是否有任何代码或示例availabel. ?

Is there any code or example availabel for ref. ?

请提供任何示例.

预先感谢

推荐答案

如果必须使用HttpWebRequest并假设输入数据流不大,则可以通过执行此操作使上传过程异步.请注意,BeginGetResponse实际上是打开与远程服务器的连接并处理上载的内容.

If you have to use HttpWebRequest and assuming your input data stream is not large you can make the upload process Async by doing this. Notice the BeginGetResponse is what actually opens the connection to the remote server and processes the upload.

public void UploadAsync()
{
    var data = GetStream("TestFile.txt");

    var request = (HttpWebRequest)WebRequest.Create(new Uri("http://example.com/UploadData"));
    request.Method = "POST";
    data.CopyTo(request.GetRequestStream());

    request.BeginGetResponse(DataUploadCompleted, request);

    Console.WriteLine("Upload Initiated.");
}

private void DataUploadCompleted(IAsyncResult ar)
{
    var request = (HttpWebRequest)ar.AsyncState;
    var response = request.EndGetResponse(ar);
    Console.WriteLine("Upload Complete.");
}

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

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