是否有任何类,库或一些代码片段,将帮助我上传文件与HTTPWebrequest?
编辑2:
我不想上传到WebDAV文件夹或类似的东西。我想模拟一个浏览器,就像你上传你的头像到一个论坛或通过一个web应用程序中的表单上传一个文件。上传到一个使用multipart/form-data的表单。
编辑:
WebClient不覆盖我的需求,所以我正在寻找一个解决方案与HTTPWebrequest。
是否有任何类,库或一些代码片段,将帮助我上传文件与HTTPWebrequest?
编辑2:
我不想上传到WebDAV文件夹或类似的东西。我想模拟一个浏览器,就像你上传你的头像到一个论坛或通过一个web应用程序中的表单上传一个文件。上传到一个使用multipart/form-data的表单。
编辑:
WebClient不覆盖我的需求,所以我正在寻找一个解决方案与HTTPWebrequest。
当前回答
基于上面提供的代码,我添加了对多个文件的支持,也可以直接上传流,而不需要有本地文件。
要将文件上传到包含一些post参数的特定url,请执行以下操作:
RequestHelper.PostMultipart(
"http://www.myserver.com/upload.php",
new Dictionary<string, object>() {
{ "testparam", "my value" },
{ "file", new FormFile() { Name = "image.jpg", ContentType = "image/jpeg", FilePath = "c:\\temp\\myniceimage.jpg" } },
{ "other_file", new FormFile() { Name = "image2.jpg", ContentType = "image/jpeg", Stream = imageDataStream } },
});
为了进一步增强这一点,可以从给定的文件本身确定名称和mime类型。
public class FormFile
{
public string Name { get; set; }
public string ContentType { get; set; }
public string FilePath { get; set; }
public Stream Stream { get; set; }
}
public class RequestHelper
{
public static string PostMultipart(string url, Dictionary<string, object> parameters) {
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
if(parameters != null && parameters.Count > 0) {
using(Stream requestStream = request.GetRequestStream()) {
foreach(KeyValuePair<string, object> pair in parameters) {
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
if(pair.Value is FormFile) {
FormFile file = pair.Value as FormFile;
string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(bytes, 0, bytes.Length);
byte[] buffer = new byte[32768];
int bytesRead;
if(file.Stream == null) {
// upload from file
using(FileStream fileStream = File.OpenRead(file.FilePath)) {
while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
fileStream.Close();
}
}
else {
// upload from given stream
while((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
}
}
else {
string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
requestStream.Write(bytes, 0, bytes.Length);
}
}
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
}
}
using(WebResponse response = request.GetResponse()) {
using(Stream responseStream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(responseStream))
return reader.ReadToEnd();
}
}
}
其他回答
我永远不能让例子正常工作,我总是收到一个500错误时,把它发送到服务器。
然而,我在这个url中遇到了一个非常优雅的方法
它很容易扩展,显然可以处理二进制文件和XML。
你可以用类似的方法来称呼它
class Program
{
public static string gsaFeedURL = "http://yourGSA.domain.com:19900/xmlfeed";
static void Main()
{
try
{
postWebData();
}
catch (Exception ex)
{
}
}
// new one I made from C# web service
public static void postWebData()
{
StringDictionary dictionary = new StringDictionary();
UploadSpec uploadSpecs = new UploadSpec();
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes;
Uri gsaURI = new Uri(gsaFeedURL); // Create new URI to GSA feeder gate
string sourceURL = @"C:\FeedFile.xml"; // Location of the XML feed file
// Two parameters to send
string feedtype = "full";
string datasource = "test";
try
{
// Add the parameter values to the dictionary
dictionary.Add("feedtype", feedtype);
dictionary.Add("datasource", datasource);
// Load the feed file created and get its bytes
XmlDocument xml = new XmlDocument();
xml.Load(sourceURL);
bytes = Encoding.UTF8.GetBytes(xml.OuterXml);
// Add data to upload specs
uploadSpecs.Contents = bytes;
uploadSpecs.FileName = sourceURL;
uploadSpecs.FieldName = "data";
// Post the data
if ((int)HttpUpload.Upload(gsaURI, dictionary, uploadSpecs).StatusCode == 200)
{
Console.WriteLine("Successful.");
}
else
{
// GSA POST not successful
Console.WriteLine("Failure.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
类似这样的代码很接近:(未测试的代码)
byte[] data; // data goes here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = userNetworkCredentials;
request.Method = "PUT";
request.ContentType = "application/octet-stream";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data,0,data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
temp = reader.ReadToEnd();
reader.Close();
我最近不得不处理这个问题——另一种方法是使用WebClient是可继承的这一事实,并从那里改变底层的WebRequest:
http://msdn.microsoft.com/en-us/library/system.net.webclient.getwebrequest (VS.80) . aspx
我更喜欢c#,但如果你坚持使用VB,结果将是这样的:
Public Class BigWebClient
Inherits WebClient
Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
Dim x As WebRequest = MyBase.GetWebRequest(address)
x.Timeout = 60 * 60 * 1000
Return x
End Function
End Class
'Use BigWebClient here instead of WebClient
查看MyToolkit库:
var request = new HttpPostRequest("http://www.server.com");
request.Data.Add("name", "value"); // POST data
request.Files.Add(new HttpPostFile("name", "file.jpg", "path/to/file.jpg"));
await Http.PostAsync(request, OnRequestFinished);
http://mytoolkit.codeplex.com/wikipage?title=Http
我写了一个类使用WebClient方式做多部分的表单上传。
http://ferozedaud.blogspot.com/2010/03/multipart-form-upload-helper.html
///
/// MimePart
/// Abstract class for all MimeParts
///
abstract class MimePart
{
public string Name { get; set; }
public abstract string ContentDisposition { get; }
public abstract string ContentType { get; }
public abstract void CopyTo(Stream stream);
public String Boundary
{
get;
set;
}
}
class NameValuePart : MimePart
{
private NameValueCollection nameValues;
public NameValuePart(NameValueCollection nameValues)
{
this.nameValues = nameValues;
}
public override void CopyTo(Stream stream)
{
string boundary = this.Boundary;
StringBuilder sb = new StringBuilder();
foreach (object element in this.nameValues.Keys)
{
sb.AppendFormat("--{0}", boundary);
sb.Append("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\";", element);
sb.Append("\r\n");
sb.Append("\r\n");
sb.Append(this.nameValues[element.ToString()]);
sb.Append("\r\n");
}
sb.AppendFormat("--{0}", boundary);
sb.Append("\r\n");
//Trace.WriteLine(sb.ToString());
byte [] data = Encoding.ASCII.GetBytes(sb.ToString());
stream.Write(data, 0, data.Length);
}
public override string ContentDisposition
{
get { return "form-data"; }
}
public override string ContentType
{
get { return String.Empty; }
}
}
class FilePart : MimePart
{
private Stream input;
private String contentType;
public FilePart(Stream input, String name, String contentType)
{
this.input = input;
this.contentType = contentType;
this.Name = name;
}
public override void CopyTo(Stream stream)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Content-Disposition: {0}", this.ContentDisposition);
if (this.Name != null)
sb.Append("; ").AppendFormat("name=\"{0}\"", this.Name);
if (this.FileName != null)
sb.Append("; ").AppendFormat("filename=\"{0}\"", this.FileName);
sb.Append("\r\n");
sb.AppendFormat(this.ContentType);
sb.Append("\r\n");
sb.Append("\r\n");
// serialize the header data.
byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString());
stream.Write(buffer, 0, buffer.Length);
// send the stream.
byte[] readBuffer = new byte[1024];
int read = input.Read(readBuffer, 0, readBuffer.Length);
while (read > 0)
{
stream.Write(readBuffer, 0, read);
read = input.Read(readBuffer, 0, readBuffer.Length);
}
// write the terminating boundary
sb.Length = 0;
sb.Append("\r\n");
sb.AppendFormat("--{0}", this.Boundary);
sb.Append("\r\n");
buffer = Encoding.ASCII.GetBytes(sb.ToString());
stream.Write(buffer, 0, buffer.Length);
}
public override string ContentDisposition
{
get { return "file"; }
}
public override string ContentType
{
get {
return String.Format("content-type: {0}", this.contentType);
}
}
public String FileName { get; set; }
}
///
/// Helper class that encapsulates all file uploads
/// in a mime part.
///
class FilesCollection : MimePart
{
private List files;
public FilesCollection()
{
this.files = new List();
this.Boundary = MultipartHelper.GetBoundary();
}
public int Count
{
get { return this.files.Count; }
}
public override string ContentDisposition
{
get
{
return String.Format("form-data; name=\"{0}\"", this.Name);
}
}
public override string ContentType
{
get { return String.Format("multipart/mixed; boundary={0}", this.Boundary); }
}
public override void CopyTo(Stream stream)
{
// serialize the headers
StringBuilder sb = new StringBuilder(128);
sb.Append("Content-Disposition: ").Append(this.ContentDisposition).Append("\r\n");
sb.Append("Content-Type: ").Append(this.ContentType).Append("\r\n");
sb.Append("\r\n");
sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");
byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
stream.Write(headerBytes, 0, headerBytes.Length);
foreach (FilePart part in files)
{
part.Boundary = this.Boundary;
part.CopyTo(stream);
}
}
public void Add(FilePart part)
{
this.files.Add(part);
}
}
///
/// Helper class to aid in uploading multipart
/// entities to HTTP web endpoints.
///
class MultipartHelper
{
private static Random random = new Random(Environment.TickCount);
private List formData = new List();
private FilesCollection files = null;
private MemoryStream bufferStream = new MemoryStream();
private string boundary;
public String Boundary { get { return boundary; } }
public static String GetBoundary()
{
return Environment.TickCount.ToString("X");
}
public MultipartHelper()
{
this.boundary = MultipartHelper.GetBoundary();
}
public void Add(NameValuePart part)
{
this.formData.Add(part);
part.Boundary = boundary;
}
public void Add(FilePart part)
{
if (files == null)
{
files = new FilesCollection();
}
this.files.Add(part);
}
public void Upload(WebClient client, string address, string method)
{
// set header
client.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + this.boundary);
Trace.WriteLine("Content-Type: multipart/form-data; boundary=" + this.boundary + "\r\n");
// first, serialize the form data
foreach (NameValuePart part in this.formData)
{
part.CopyTo(bufferStream);
}
// serialize the files.
this.files.CopyTo(bufferStream);
if (this.files.Count > 0)
{
// add the terminating boundary.
StringBuilder sb = new StringBuilder();
sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");
byte [] buffer = Encoding.ASCII.GetBytes(sb.ToString());
bufferStream.Write(buffer, 0, buffer.Length);
}
bufferStream.Seek(0, SeekOrigin.Begin);
Trace.WriteLine(Encoding.ASCII.GetString(bufferStream.ToArray()));
byte [] response = client.UploadData(address, method, bufferStream.ToArray());
Trace.WriteLine("----- RESPONSE ------");
Trace.WriteLine(Encoding.ASCII.GetString(response));
}
///
/// Helper class that encapsulates all file uploads
/// in a mime part.
///
class FilesCollection : MimePart
{
private List files;
public FilesCollection()
{
this.files = new List();
this.Boundary = MultipartHelper.GetBoundary();
}
public int Count
{
get { return this.files.Count; }
}
public override string ContentDisposition
{
get
{
return String.Format("form-data; name=\"{0}\"", this.Name);
}
}
public override string ContentType
{
get { return String.Format("multipart/mixed; boundary={0}", this.Boundary); }
}
public override void CopyTo(Stream stream)
{
// serialize the headers
StringBuilder sb = new StringBuilder(128);
sb.Append("Content-Disposition: ").Append(this.ContentDisposition).Append("\r\n");
sb.Append("Content-Type: ").Append(this.ContentType).Append("\r\n");
sb.Append("\r\n");
sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");
byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
stream.Write(headerBytes, 0, headerBytes.Length);
foreach (FilePart part in files)
{
part.Boundary = this.Boundary;
part.CopyTo(stream);
}
}
public void Add(FilePart part)
{
this.files.Add(part);
}
}
}
class Program
{
static void Main(string[] args)
{
Trace.Listeners.Add(new ConsoleTraceListener());
try
{
using (StreamWriter sw = new StreamWriter("testfile.txt", false))
{
sw.Write("Hello there!");
}
using (Stream iniStream = File.OpenRead(@"c:\platform.ini"))
using (Stream fileStream = File.OpenRead("testfile.txt"))
using (WebClient client = new WebClient())
{
MultipartHelper helper = new MultipartHelper();
NameValueCollection props = new NameValueCollection();
props.Add("fname", "john");
props.Add("id", "acme");
helper.Add(new NameValuePart(props));
FilePart filepart = new FilePart(fileStream, "pics1", "text/plain");
filepart.FileName = "1.jpg";
helper.Add(filepart);
FilePart ini = new FilePart(iniStream, "pics2", "text/plain");
ini.FileName = "inifile.ini";
helper.Add(ini);
helper.Upload(client, "http://localhost/form.aspx", "POST");
}
}
catch (Exception e)
{
Trace.WriteLine(e);
}
}
}
这将适用于所有版本的. net框架。