gpt4 book ai didi

c# - WebClient上传文件错误

转载 作者:行者123 更新时间:2023-11-30 15:12:14 25 4
gpt4 key购买 nike

我正在使用 VSTS 2008 + C# + .Net 3.5 + ASP.Net + IIS 7.0 在客户端开发控制台应用程序以上传文件,并在服务器端使用 aspx 文件接收此文件。

在客户端,我总是注意到(从控制台输出)文件的上传百分比从 1% 增加到 50%,然后突然增加到 100%。有什么想法吗?

这是我的客户端代码,

class Program
{
private static WebClient client = new WebClient();
private static ManualResetEvent uploadLock = new ManualResetEvent(false);

private static void Upload()
{
try
{
Uri uri = new Uri("http://localhost/Default.aspx");
String filename = @"C:\test\1.dat";

client.Headers.Add("UserAgent", "TestAgent");
client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCompleteCallback);
client.UploadFileAsync(uri, "POST", filename);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace.ToString());
}
}

public static void UploadFileCompleteCallback(object sender, UploadFileCompletedEventArgs e)
{
Console.WriteLine("Completed! ");
uploadLock.Set();
}

private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine (e.ProgressPercentage);
}

static void Main(string[] args)
{
Upload();

uploadLock.WaitOne();

return;
}
}

这是我的服务器端代码,

    protected void Page_Load(object sender, EventArgs e)
{
string agent = HttpContext.Current.Request.Headers["UserAgent"];
using (FileStream file = new FileStream(@"C:\Test\Agent.txt", FileMode.Append, FileAccess.Write))
{
byte[] buf = Encoding.UTF8.GetBytes(agent);
file.Write(buf, 0, buf.Length);
}

foreach (string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs("C:\\Test\\UploadFile.dat");
}
}

提前致谢,乔治

最佳答案

这是一个已知的 bug在 WebClient 类中。它将在 .NET 4.0 中得到修复。在那之前你可以使用 HttpWebRequest实现此功能。


更新:这是使用同步 HttpWebRequest 上传文件并跟踪进度的示例:

public sealed class Uploader
{
public const int CHUNK_SIZE = 1024; // 1 KB

public void Upload(string url, string filename, Stream streamToUpload, Action<int> progress)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string boundary = string.Format("---------------------{0}", DateTime.Now.Ticks.ToString("x"));
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
request.KeepAlive = true;

using (var requestStream = request.GetRequestStream())
{
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, filename);
var headerBytes = Encoding.ASCII.GetBytes(header);
requestStream.Write(headerBytes, 0, headerBytes.Length);

byte[] buffer = new byte[CHUNK_SIZE];
int bytesRead;
long total = streamToUpload.Length;
long totalBytesRead = 0;
while ((bytesRead = streamToUpload.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bytesRead;
progress((int)(100 * totalBytesRead / total));
byte[] actual = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
requestStream.Write(actual, 0, actual.Length);
}
}
using (var response = request.GetResponse()) { }
}
}

class Program
{
static void Main(string[] args)
{
var url = "http://localhost:2141/Default.aspx";
var filename = "1.dat";
var uploader = new Uploader();
using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
uploader.Upload(url, filename, fileStream, progress => Console.WriteLine("{0}% of \"{1}\" uploaded to {2}", progress, filename, url));
}
}
}

关于c# - WebClient上传文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1542853/

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