Asynchronous Upload of Large File Using HttpWebRequest in C#.Net [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
开发者_开发知识库 Improve this questionI want to upload a large file in asynchronous way using HttpWebRequest.
Say i upload a audio file from using HttpWebRequest & on the receiver end it should get the stream & play the audio file.
Is there any code or example availabel for ref. ?
Please provide if any example.
Thanks in advance
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.");
}
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;
}
精彩评论