返回pdf字节数组WCF

返回pdf字节数组WCF

问题描述:

我正在使用Web服务WCF返回字节数组格式的PDF文件.我只是返回了我在这样的资源中拥有的​​pdf文件:

I am using a web service, WCF, to return a PDF file in byte array format. I was just returning the pdf file that I had in resources like this:

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

但是在客户端,当我接收到字节数组并将其写入计算机上的文件时,使用此命令:

However on the client side when I receive the byte array and write it to a file on my computer using this:

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,因为它不受支持的文件类型或它可能已损坏.

It writes out a PDF file to My Documents, but when I click on it it says can't view PDF because it is not supported file type or it may be corrupted.

我已经看到一些关于使用流发送而不是发送字节数组的文章.我想知道是否有任何有关如何正确执行此操作的示例,以便我可以将字节数组或流或您提出的任何建议写到客户端的pdf文件中,然后通过单击手动打开该文件.

I have seen some posts about instead of sending a byte array, to send it using stream. I was wondering if there was any examples on how to do this properly, so that I can write the byte array or stream or whatever you suggest out to a pdf file on the client side, then manually open the file by clicking on it.

注意:我正在使用REST访问Web服务.因此,添加服务参考不是一种选择.

Note: I am accessing the Web service using REST. So adding a Service Reference is not an option.

好,我找到了答案,并尝试了一下,它确实起作用了.因此,答案是您应该使用Stream而不是字节数组.对于其他想要示例的人,我在服务器端对此进行了修改:

Ok I found the answer, and tried it and it does work. So the answer is that you should be using a Stream instead of a byte array. For anyone else that wants an example I modified my code to this on the server side:

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);
}