【发布时间】:2019-03-03 05:35:52
【问题描述】:
我需要一个函数来将大数据文件上传到服务器,作为来自外部服务提供商的带有 POST 的 HTTP 上传。 在我使用以下 webclient 功能的那一刻,它适用于较小的文件:
_byteReturn = await _webClient.UploadDataTaskAsync(_url, File.ReadAllBytes(@"c:\tmp\test.zip"));
但在这种情况下存在 2GB 边界的问题,函数 ReadAllBytes() 将所有字节读取到内存中。 当然我可以使用另一个 weblient 功能
_byteReturn = await _webClient.UploadFileTaskAsync(_url, @"c:\tmp\test.zip"));
但使用该功能,我从服务器收到 HTTP 错误 400。 :/ 所以它尝试使用我自己的代码进行上传。
using (WebClient _webClient = new WebClient())
{
_webClient.Headers[HttpRequestHeader.UserAgent] = "Test";
_webClient.Headers[HttpRequestHeader.CacheControl] = "no-cache";
_webClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("Username") + ":" + ("Password" )));
using (StreamWriter _output = new StreamWriter(await _webClient.OpenWriteTaskAsync(_url)))
{
_output.AutoFlush = true;
using (FileStream _fileStream = new FileStream(@"c:\tmp\install.esd", FileMode.Open, FileAccess.Read))
{
_bytesRead = 0;
_readByteBuffer = new byte[_bufferLength];
_bytesToRead = _fileStream.Length;
#if DEBUG
FileStream _testOutFileStream = new FileStream(_writeTestFileNameZip, FileMode.OpenOrCreate, FileAccess.ReadWrite);
#endif
do
{
_fileStream.Seek(_bytesRead, SeekOrigin.Begin);
_readCount = _fileStream.Read(_readByteBuffer, 0, _bufferLength);
_output.Write(_readByteBuffer);
#if DEBUG
if (_testOutFileStream != null)
{
_testOutFileStream.Write(_readByteBuffer, 0, _readCount);
_testOutFileStream.Flush();
}
#endif
_bytesRead += _readCount;
}
while (_readCount > 0);
#if DEBUG
if (_testOutFileStream != null)
_testOutFileStream.Dispose();
#endif
}
if (_output != null)
_output.Close();
}
}
重点是“它可以工作”。我在上传过程中没有收到任何错误,上传完成后我从服务器得到了正确的答案,但是上传速度非常快。(在 10 秒内以 10MBit/s 的速度上传 1GB)。
我相信这是一个缓存问题,但我不确定。谁知道问题出在哪里?
【问题讨论】:
标签: c# file-upload webclient