Re: [問題] Http file upload 問題
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();
}
--
◤◥ Origin: 幽谷˙反地球聯邦組織 aeug.twbbs.org
◣◢ Author: GP03 從 221.220.251.202 發表
討論串 (同標題文章)
完整討論串 (本文為第 5 之 8 篇):