4

我在将 PhantomJS 生成的文件下载到我的 asp.net 应用程序时遇到了一些问题。我正在将 phantomJs 作为服务器运行:该文件已正确生成并保存到 PhantomJS 文件夹中的磁盘,但是在传输和包含到我的 Http 响应流中时发生了一些事情。该文件是由浏览器下载的,但是当我尝试打开它时,文件错误并显示无法打开的消息。我怀疑它在流传输中被损坏了?

我想避免从文件系统中的存储位置读取 pdf,而是从 PhantomJS 返回的响应中获取它

幻影JS代码:

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

1 回答 1

2

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);
于 2013-07-06T22:00:06.123 回答