Re: [問題] Http file upload 問題

看板Programming作者時間17年前 (2008/06/06 18:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/8 (看更多)
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: GP03221.220.251.202 發表
文章代碼(AID): #18IGh-00 (Programming)
討論串 (同標題文章)
文章代碼(AID): #18IGh-00 (Programming)