C#使用HttpWebRequest和HttpWebResponse上传文件示例
1.HttpHelper类:
2.调用示例:
参考资料
[1].ASP无组件上传原理: http://www.jjshang.com/jjshangnew/book/asp/mustfiles/jjupload.pdf
[2].Upload files with HTTPWebrequest (multipart/form-data): http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
复制内容到剪贴板程序代码
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
namespace ConsoleApplication1
{
public static class HttpHelper
{
private static readonly Encoding DEFAULTENCODE = Encoding.UTF8;
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data)
{
return HttpUploadFile(url, file, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data, Encoding encoding)
{
return HttpUploadFile(url, new string[] { file }, data, encoding);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data)
{
return HttpUploadFile(url, files, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
//1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (data != null)
{
foreach (string key in data.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, data[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
//1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[4096];
int bytesRead = 0;
for (int i = 0; i < files.Length; i++)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
}
//1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
}
}
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
namespace ConsoleApplication1
{
public static class HttpHelper
{
private static readonly Encoding DEFAULTENCODE = Encoding.UTF8;
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data)
{
return HttpUploadFile(url, file, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data, Encoding encoding)
{
return HttpUploadFile(url, new string[] { file }, data, encoding);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data)
{
return HttpUploadFile(url, files, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
//1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (data != null)
{
foreach (string key in data.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, data[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
//1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[4096];
int bytesRead = 0;
for (int i = 0; i < files.Length; i++)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
}
//1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
}
}
2.调用示例:
复制内容到剪贴板程序代码
using System;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NameValueCollection data = new NameValueCollection();
data.Add("name", "木子屋");
data.Add("url", "http://www.mzwu.com/");
Console.WriteLine(HttpHelper.HttpUploadFile("http://localhost/Test", new string[] { @"E:\Index.htm", @"E:\test.rar" }, data));
Console.ReadKey();
}
}
}
using System.Collections.Specialized;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NameValueCollection data = new NameValueCollection();
data.Add("name", "木子屋");
data.Add("url", "http://www.mzwu.com/");
Console.WriteLine(HttpHelper.HttpUploadFile("http://localhost/Test", new string[] { @"E:\Index.htm", @"E:\test.rar" }, data));
Console.ReadKey();
}
}
}
参考资料
[1].ASP无组件上传原理: http://www.jjshang.com/jjshangnew/book/asp/mustfiles/jjupload.pdf
[2].Upload files with HTTPWebrequest (multipart/form-data): http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
来源:oschina
链接:https://my.oschina.net/u/4413091/blog/3384389