C#.Net中使用HttpWebRequest异步上传大文件

发布于 2024-11-03 14:05:24 字数 1539 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

指尖微凉心微凉 2024-11-10 14:05:24

如果您必须使用 HttpWebRequest 并假设您的输入数据流不大,您可以通过这样做使上传过程异步。请注意,BeginGetResponse 是实际打开与远程服务器的连接并处理上传的内容。

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.");
}

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.");
}
寄与心 2024-11-10 14:05:24

它必须是 HttpWebRequest 吗?您可以使用 WebClient 对象轻松完成此操作

public void UploadFile(byte[] fileData)
{
    var client = new WebClient();
    client.UploadDataCompleted += client_UploadDataCompleted;
    client.UploadDataAsync(new Uri("http://myuploadlocation.example.com/"), fileData);
}

void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }

    byte[] response = e.Result;
}

Does it have to be a HttpWebRequest? You can do this very easily with the WebClient object

public void UploadFile(byte[] fileData)
{
    var client = new WebClient();
    client.UploadDataCompleted += client_UploadDataCompleted;
    client.UploadDataAsync(new Uri("http://myuploadlocation.example.com/"), fileData);
}

void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }

    byte[] response = e.Result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文