2009-07-30 19 views

回答

2

如果該文件是足夠小你可以很容易地適應它在內存中(你會希望它是,如果你通過郵遞),那麼你可以簡單地做到以下幾點:

string textFileContents = System.IO.File.ReadAllText(@"C:\MyFolder\MyFile.txt"); 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.myserver.com/myurl.aspx"); 
request.Method = "POST"; 

ASCIIEncoding encoding = new ASCIIEncoding(); 

string postData = "fileContents=" + System.Web.HttpUtility.UrlEncode(textFileContents); 

byte[] data = encoding.GetBytes(postData); 

request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = data.Length; 

Stream dataStream = request.GetRequestStream(); 

dataStream.Write(data, 0, data.Length); 

dataStream.Close(); 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

// do something with the response if required 

至於閱讀的文本服務器端就可以只需使用Page.Request.Form [「fileContents」]

0

我很困惑;你說你想要它作爲POST參數,但是然後你從頭文件中讀取它......?這將是典型的後場的形式,或者只是原始數據請求體...

要發送表單字段:

NameValueCollection fields = new NameValueCollection(); 
    fields.Add("name1","some text"); 
    fields.Add("name2","some more text"); 
    using (var client = new WebClient()) 
    { 
     byte[] resp = client.UploadValues(address, fields); 
     // use Encoding to get resp as a string if needed 
    } 

用於發送原始文件(而不是作爲一種形式,只是文本本身),請使用UploadFile;和標題,使用.Headers.Add

0

如果您的webmethod使用HttpContext.Current.Request.Headers["errorLog"],那麼您的客戶端應用程序在執行請求時需要發送此自定義http標頭。請注意,http標頭並不意味着發送大量數據。

在您的客戶端應用程序,你可以Web引用添加到服務,並使用生成的代理類重寫GetWebRequest,並添加自定義HTTP標頭:

protected override System.Net.WebRequest GetWebRequest(Uri uri) 
{ 
    var req = (HttpWebRequest)base.GetWebRequest(uri); 
    var value File.ReadAllText("path_to_your_file"); 
    req.Headers.Add("errorLog", value); 
    return (WebRequest)req; 
} 
相關問題