[英]Getting file returned using FileContentResult and writing it to a file
Right now, I have a web service (.asmx) that calls a mvc 4 controller action returning a PDF file via: 现在,我有一个Web服务(.asmx)调用mvc 4控制器操作,通过以下方式返回PDF文件:
return File(pdfBytes, "application/pdf", "Report.pdf");
And I'm getting the result in the web service like this: 我在Web服务中得到的结果如下:
WebResponse response = request.GetResponse();
var status = ((HttpWebResponse)response).StatusDescription;
var dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
What I want is to write the file returned into the file system. 我想要的是将返回的文件写入文件系统。 Something like this:
像这样的东西:
byte[] responseBytes = Encoding.UTF8.GetBytes(responseFromServer);
var file = File.Create("C://Report.pdf");
file.Write(responseBytes, 0, responseBytes.Length);
But the file written has all the pages in blank. 但是编写的文件将所有页面都空白。
What am I missing here? 我在这里错过了什么?
The solution to this was to get the bytes directly from the response stream. 解决方案是直接从响应流中获取字节。
Like this: 像这样:
var dataStream = response.GetResponseStream() ;
byte[] responseBytes;
using (var memoryStream = new MemoryStream())
{
dataStream.CopyTo(memoryStream);
responseBytes = memoryStream.ToArray();
return responseBytes;
}
Don't use the WebResponse
object for this. 不要使用
WebResponse
对象。 Use the WebClient
instead. 请改用
WebClient
。 It is great for downloading binary data over http
. 通过
http
下载二进制数据非常棒。 All you need to do is replace your webservice´s code with: 您需要做的就是用以下内容替换您的webservice代码:
var serverUrl = "http://localhost:60176/Demo/PdfFile"; //... replace with the request url
var client = new System.Net.WebClient();
var responseBytes = client.DownloadData(serverUrl);
System.IO.File.WriteAllBytes(@"c:\Report.pdf", responseBytes);
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.