CodeAs follows:
Public String Httpuploadfile ( String URL, String File, String Paramname, String Contenttype, namevaluecollection NVC)
{
String Result = String . Empty;
String Boundary = " --------------------------- " + Datetime. Now. ticks. tostring ( " X " );
Byte [] Boundarybytes = System. Text. encoding. ASCII. getbytes ( " \ R \ n -- " + Boundary + " \ R \ n " );
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 {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 " ;
String Header = String . Format (headertemplate, paramname, file, contenttype );
Byte [] Headerbytes = System. Text. encoding. utf8.getbytes (header );
Rs. Write (headerbytes, 0 , Headerbytes. Length );
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 ();
Webresponse wresp = Null ;
Try
{
Wresp = Wr. getresponse ();
Stream stream2 = Wresp. getresponsestream ();
Streamreader reader2 = New Streamreader (stream2 );
Result = Reader2.readtoend ();
}
Catch (Exception ex)
{
If (Wresp ! = Null )
{
Wresp. Close ();
Wresp = Null ;
}
}
Finally
{
WR = Null ;
}
ReturnResult;
}
Call:
// Call an instance
Namevaluecollection NVC = New Namevaluecollection ();
NVC. Add ( " ID " , " TTR " );
NVC. Add ( " BTN-submit-photo " , " Upload " );
Httpuploadfile ( " Http://your.server.com/upload " ,
@" C: \ test \ test.jpg " , " File " , " Image/JPEG " , NVC );
Refer:
HTTP://Bytes
From: http://www.cnblogs.com/94cool/archive/2011/03/05/1971873.html