看板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 發表