我在将一个PhantomJS生成的文件下载到我的asp.net应用程序时遇到了一些麻烦。 我正在运行phantomJs作为服务器: 该文件生成正确并保存到PhantomJS文件夹中的磁盘,但在传输和包含到我的Http响应流期间发生了一些事情。该文件由浏览器下载,但是当我尝试打开它时,文件错误,并显示无法打开的消息。我怀疑它在流传输中被破坏了吗?
我想避免从文件系统中存储的位置读取pdf,而是将其从PhantomJS返回的响应中删除
PhantomJS代码:
page.open(url, function (status) {
page.render(fullFileName);
var fs = require('fs');
var pdfContent = fs.read(fullFileName);
response.statusCode = 200;
response.headers = {
'Cache': 'no-cache',
'Content-Type': 'application/pdf',
'Connection': 'Keep-Alive',
'Content-Length': pdfContent.length
};
response.setEncoding("binary");
response.write(pdfContent);
});
ASP.NET代码:
public ActionResult DownloadPdfFromUrl(ConvertionModel model)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:8080");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = string.Format("url={0}&fileName=myTest&extension=pdf&format=pdf", model.UrlToConvertPdf);
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream s = httpWReq.GetRequestStream())
{
s.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)httpWReq.GetResponse();
Response.AppendHeader("Content-Disposition", "attachment;filename=test.pdf");
return new FileStreamResult(response.GetResponseStream(), "application/pdf");
}
答案 0 :(得分:1)
C#代码看起来不错,但最好不要返回null动作结果。我最好写
var stream = response.GetResponseStream();
var buffer = new byte[response.ContentLength];
stream.Read(buffer, 0, buffer.Length);
return File(buffer, "application/pdf", "test.pdf");
在编写文档正文之前,还要在PhantomJS中设置响应编码:
response.setEncoding("binary");
response.write(pdfContent);