我使用方法HttpUploadFile
来上传带有一些字符串参数的图像:
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
Console.Write(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] omg = boundarybytes;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
//parsing response
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
String output = reader2.ReadToEnd();
}
catch (Exception ex){
Console.Write("Error uploading file" + ex.ToString());
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
现在我想跟踪上传的进度。我找到C# HttpWebRequest Form Post with Progress Tracking (for uploading potentially large files)但该解决方案对我不起作用。
答案 0 :(得分:1)
您正在从文件中读取图像并一次上传4096个字节。在每个4096字节之后,您可以调用一些将进度条更新为新值的其他函数。
首先,您需要知道文件的大小。无论何时上传包,您都可以通过汇总所有已发送的包并将它们与要发送的总字节数进行比较来计算百分比。
正如我刚刚从您链接的主题中看到的那样,在您调用GetResponse之前,HttpWebRequest可能无法实际发送数据。
为了防止您可以尝试立即发送数据,请使用一些解决方法,例如设置Content-Length(这意味着您需要知道预先发送了多少数据),或者可能通过设置传输 - 编码到chunked(不知道这是否有效)。您也可以使用原始套接字,这样您就可以完全控制。发送这样的请求要多得多,但不是很复杂。
如果我以后有一段时间你决定使用原装插座,我可以为你准备一个小例子。