看板Programming
标 题Re: [问题] Http file upload 问题
发信站反地球联邦组织 (Wed Jun 4 04:45:21 2008)
转信站ptt!ctu-reader!ctu-gate!news.nctu!news2!ccnews.ncku!gem.nstdc.nthu!new
C#的code
byte[] body = null;
string fileName = "1.txt";
string filePath = @"c:\1.txt";
//读取档案
using( FileStream inFile = new FileStream( filePath, FileMode.Open ) )
{
byte[] inBytes = new byte[ inFile.Length ];
inFile.Read( inBytes, 0, inBytes.Length );
body = inBytes;
}
//设定上传Url
string url =@"
http://127.0.0.1/upload.aspx";
HttpWebRequest req = ( WebRequest.Create( url ) as HttpWebRequest );
string boundary = guid.Replace( "-", "" );
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Method = "POST";
MemoryStream postData = new MemoryStream();
string newLine = "\r\n";
StreamWriter sw = new StreamWriter( postData );
sw.Write( "--" + boundary + newLine );
sw.Write(
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}",
"Attatch",
fileName ,
newLine
);
sw.Write( "Content-Type: application/octet-stream" + newLine + newLine );
sw.Flush();
//读取档案至postData
postData.Write( body, 0, body.Length );
sw.Write( newLine );
sw.Write( "--{0}--{1}", boundary, newLine );
sw.Flush();
req.ContentLength = postData.Length;
try
{
using( Stream s = req.GetRequestStream() )
{
postData.WriteTo( s );
}
}
catch( WebException ex )
{
messgae = ex.Message;
return false;
}
postData.Close();
HttpWebResponse resp = null;
StreamReader sr = null;
bool ret = false;
try
{
//上传
resp = (HttpWebResponse)req.GetResponse();
sr = new StreamReader( resp.GetResponseStream() );
string htmlRet = sr.ReadToEnd();
}
catch( Exception ex )
{
messgae = ex.Message;
ret = false;
}
finally
{
sr.Close();
resp.Close();
}
--
◤◥ Or
igin:
幽谷˙反地球联邦组织 aeug.twbbs.org
◣◢ A
uthor:
GP03 从
221.220.251.202 发表