问题
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);
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.
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.
Note: I am accessing the Web service using REST. So adding a Service Reference is not an option.
回答1:
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;
}
And to this on the Client Side:
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);
}
来源:https://stackoverflow.com/questions/35509088/return-pdf-byte-array-wcf