2016-02-19 38 views
0

我正在使用Web服務WCF以字節數組格式返回PDF文件。在客戶端返回pdf字節數組WCF

public byte[] displayPDF(string pdfName){ 
    return Service.Properties.Resources.testFile; 
} 

然而,當我收到的字節數組,並利用這一點,寫在我的電腦上的文件:我剛剛回來,我有資源這樣的PDF文件

HttpClient client = new HttpClient(); 
client.MaxResponseContentBufferSize = 9999999; 
var uri = new Uri("http://TestSite.azurewebsites.net/Service.svc/webHttp/displayPDF?pdfName=testFile.pdf"); 
var response = client.GetAsync(uri); 
byte[] byteArray = response.Result.Content.ReadAsByteArrayAsync().Result; 
var filePath = "C:\\Users\\Admin 1\\Documents\\temp.pdf"; 
System.IO.File.WriteAllBytes(filePath, byteArray); 

它向我的文檔寫出PDF文件,但是當我點擊它時,它說無法查看PDF,因爲它不受支持的文件類型,或者它可能已損壞。

我已經看到了一些關於發送字節數組而不是發送使用流的帖子。我想知道是否有任何關於如何正確執行此操作的示例,以便我可以將字節數組或流或任何您建議的內容寫入客戶端的pdf文件,然後通過單擊該文件手動打開該文件。

說明:我正在使用REST訪問Web服務。因此添加服務引用不是一個選項。

+1

檢查這篇文章的http://www.topwcftutorials。 net/2014/03/download-large-file-in-wcf.html – Agalo

+0

感謝您的建議,但我無法像您的鏈接建議一樣向客戶端添加服務引用。我已經相應地更新了我的帖子。 – User9813

+0

這是什麼類型的「服務」? – anhtv13

回答

0

好吧,我找到了答案,並嘗試它,它確實有效。所以答案是你應該使用流而不是字節數組。對於任何人想要我修改了代碼,這在服務器端的例子:

public Stream displayPDF(string pdfName) 
{ 
    MemoryStream ms = new MemoryStream(); 
    ms.Write(Service.Properties.Resources.testFile, 0, Service.Properties.Resources.testFile.Length); 
    ms.Position = 0; 
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; 
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=" + pdfName); 
    return ms;       
} 

而且這個客戶端上的:

Console.WriteLine("Started"); 
HttpClient client = new HttpClient(); 
client.MaxResponseContentBufferSize = 9999999; 
var uri = new Uri("http://TestSite.azurewebsites.net/Service.svc/webHttp/displayPDF?pdfName=testFile.pdf"); 
var responseTask = client.GetStreamAsync(uri); 
var response = responseTask.Result; 
using (System.IO.FileStream output = new System.IO.FileStream(@"C:\Users\Admin 1\Documents\MyOutput.pdf", FileMode.Create)) 
{ 
    response.CopyTo(output); 
} 
+0

「Service.Properties.Resources.testFile」中的「Service」的類型是什麼? – anhtv13

相關問題