将大文件发送到服务器

时间:2016-05-29 12:44:10

标签: c# sockets file-upload httpwebrequest

我正在尝试从我的Xamarin Android应用程序向Asp.net服务器发送大文件。我发现最好的方法是以块的形式发送文件而不是整个发送。我正在使用教程here,它使用HttpWebRequest将请求发送到服务器。在本教程的以下代码行中,文件以块的形式发送到服务器:

/ Send the file binaries over to the server, in 1024 bytes chunk
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
    FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
    s.Write(buffer, 0, bytesRead);
} // end while
fileStream.Close();

我知道s.Write(buffer, 0, bytesRead)在网络套接字上写入了这个字节,但来回通信是如何工作的?客户端是否等待服务器响应并将下一个块发送到服务器,或者所有块都写在网络流上并一起发送? 现在我收到的服务器代码是完整文件而不是它的块。我的服务器端代码如下所示:

public async Task<HttpResponseMessage> UploadFile()
    {
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
                // NOTE: To store in memory use postedFile.InputStream
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }

        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

如何在文件发送时确保连接没有超时,这是将大文件发送到服务器的最有效方法吗?如果客户端的netowrk连接中有一个小飞艇,我怎么能恢复上传?

0 个答案:

没有答案