HttpWebRequest - sending file by chunks and tracki

2019-08-28 16:40发布

I have the following code that uploads the file to the server by making the POST request:

string fileName = @"C:\Console_sk.txt";

HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create("http://" + Environment.MachineName + ":8000/Upload");
request.Method = "POST";
request.ContentType = "text/plain";
request.AllowWriteStreamBuffering = false;

Stream fileStream = new FileStream(fileName, FileMode.Open);
request.ContentLength = fileStream.Length;

Stream serverStream  = request.GetRequestStream();

byte[] buffer = new byte[4096];
while (true)
{
    int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
    if (bytesRead > 0)
    {
        serverStream.Write(buffer, 0, bytesRead);     
    }
    else
    {
        break;
    }
}

serverStream.Close();
fileStream.Close();

request.GetResponse();

This will be used to upload potentially large files, therefore it is essential for us to track the progress of this upload.

Based on various sources, I've thought that my code will upload file in 4096 byte chunks i.e. multiple POST requests will be made. But when tracking requests by using Fiddler, it shows that only one POST request is made. On other hand, when I enabled .NET network tracing, the resulting log showed that 4096 byte chunks are indeed written to request stream and the socket is always being opened for each write operation.

My understanding of networking in general is quite poor, so I don't quite understand how this really works. When calling serverStream.Write, is the provided chunk really sent over the network, or is it just buffered somewhere? And when serverStream.Close is called, can I be sure that the whole file has been uploaded?

1条回答
闹够了就滚
2楼-- · 2019-08-28 17:23

The HttpWebRequest class sends a single HTTP request. What you are doing is that you are writing to the request in chunks to avoid loading the whole file in memory. You are reading from the file and directly writing to the request stream in chunks of 4KB.

When calling serverStream.Write, is the provided chunk really sent over the network

Yes, it is written to the network socket.

查看更多
登录 后发表回答