2010-11-25 80 views
1

我需要將pdf文件和電話號碼上傳到將發送傳真的服務。如何在同一篇文章中上傳數據和文件?

的作品(從網頁)的形式如下:

<form action="send.php" method="post" enctype="multipart/form-data"> 
    <input type="file" name="pdf" id="pdf" /> 
    <input type="text" name="phonenumber" id="phonenumber" /> 
    <input type="submit" name="Submit" /> 
</form> 

的問題是,我需要從C#編寫Windows應用程序做到這一點。

如何在同一篇文章中同時上傳文件和字符串?我正在使用WebClient類。
我試圖打開這個文件,讀取它的字節,這樣發佈的一切:

string content = "phonenumber="+request.PhoneNumber+"&pdf="; 

WebClient c = new WebClient(); 
c.Headers.Add("Content-Type", "multipart/form-data"); 
c.Headers.Add("Cache-Control", "no-cache"); 
c.Headers.Add("Pragma", "no-cache"); 

byte[] bret = null; 
byte[] p1 = Encoding.ASCII.GetBytes(content); 
byte[] p2 = null; 
using (StreamReader sr = new StreamReader(request.PdfPath)) 
{ 
    using (BinaryReader br = new BinaryReader(sr.BaseStream)) 
    { 
     p2 = br.ReadBytes((int)sr.BaseStream.Length); 
    } 
} 

byte[] all = new byte[p1.Length + p2.Length]; 
Array.Copy(p1, 0, all, 0, p1.Length); 
Array.Copy(p2, 0, all, p1.Length, p2.Length); 

bret = c.UploadData(url, "POST", all); 

這是行不通的。

我沒有服務器日誌或類似的東西來幫助我調試它。

我是否缺少WebClient類的簡單東西?是否有任何其他方式來結合UploadFileUploadData來發布像網頁(有效)這兩個值呢?

回答

3

首先,您在多部分/表單數據標頭中執行c.Headers.Add時會出現拼寫錯誤。 :-)

其次,您需要通過在內容部分之間引入邊界來正確地設置您的文章的格式。看看here

+0

修正了錯字,那也只是在後,而不是在代碼 - 看在現在的界限... – juan 2010-11-25 14:10:42

2

您必須使用邊界分隔上傳的數據。有關詳細信息,請參閱post

0

這可能會或可能不會有所幫助,但我發現一個錯字:

c.Headers.Add("Content-Type", "multipart/form-dat"); 

應該

c.Headers.Add("Content-Type", "multipart/form-data"); 
+0

修正了它,它只在帖子中,而不在代碼中 – juan 2010-11-25 14:10:23

相關問題