gpt4 book ai didi

c# - 上传速度问题: HttpWebRequest

转载 作者:可可西里 更新时间:2023-11-01 07:58:07 25 4
gpt4 key购买 nike

<分区>

我正在使用 HttpWebRequest 将文件上传到某个服务器,现在的问题是我遇到了速度问题。

我无法获得与浏览器 (Mozilla Firefox) 相同的上传速度,我获得的速度是浏览器速度的 1/5。

这是我的 HttpWebRequest 对象的设置

//headers is a NameValueCollection type object,
//Method is a struct { GET, POST, HEAD }

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.UserAgent = headers["User-Agent"];
request.KeepAlive = false;
request.Accept = headers["Accept"];
request.AllowAutoRedirect = AllowRedirect;
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.5");
request.Method = Method.ToString();
request.AllowWriteStreamBuffering = false;
request.ReadWriteTimeout = 60000;

我一直启用的一些全局选项

        ServicePointManager.Expect100Continue = false;
ServicePointManager.DefaultConnectionLimit = 200;
ServicePointManager.MaxServicePointIdleTime = 2000;
ServicePointManager.MaxServicePoints = 1000;
ServicePointManager.SetTcpKeepAlive(false, 0, 0);

我如何以 block 的形式发送文件...

            if (PostMethod == PostType.MultiPart && uploadFiles.Count > 0)
{
for (int i = 0; i < uploadFiles.Count; i++)
{
string fileParam = uploadFiles.GetKey(i);
string tmpFilename = uploadFiles.Get(i);
string tmpData =
string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", boundary, fileParam, Path.GetFileName(tmpFilename), MimeType.GetMimeByExtension(Path.GetExtension(tmpFilename)));
byte[] tmpBytes = Encoding.Default.GetBytes(tmpData);
writer.Write(tmpBytes, 0, tmpBytes.Length);
bSent += tmpBytes.Length;

arg.Progress = (int)(bSent * 100 / totalBytes);
arg.Speed = (bSent / sw.Elapsed.TotalSeconds);
OnProgress(arg);

//write the file
int fileBytesRead;

FileStream fileStream = File.Open(tmpFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
// buffer size = 8192
while ((fileBytesRead = fileStream.Read(buffer, 0, BUFFER_SIZE)) > 0)

{
writer.Write(buffer, 0, fileBytesRead);
bSent += fileBytesRead;

int timeNow = Environment.TickCount;
if (timeNow - lastTime >= 500)
{
lastTime = timeNow;
arg.Progress = (int)(bSent * 100 / totalBytes);
arg.Speed = (bSent / sw.Elapsed.TotalSeconds);
OnProgress(arg);
}
}

tmpBytes = Encoding.Default.GetBytes("\r\n");
writer.Write(tmpBytes, 0, tmpBytes.Length);
bSent += tmpBytes.Length;

arg.Progress = (int)(bSent * 100 / totalBytes);
arg.Speed = (bSent / sw.Elapsed.TotalSeconds);
OnProgress(arg);

}
}

我很乐意达到浏览器上传速度的 75%。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com