Bar*_*cki 6 javascript angularjs
我想使用从Web服务器下载pdf文件$http.我使用这个效果很好的代码,我的文件只保存为html文件,但是当我打开它时,它会以pdf格式打开但在浏览器中.我在Chrome 36,Firefox 31和Opera 23上进行了测试.
这是我的angularjs代码(基于此代码):
UserService.downloadInvoice(hash).success(function (data, status, headers) {
var filename,
octetStreamMime = "application/octet-stream",
contentType;
// Get the headers
headers = headers();
if (!filename) {
filename = headers["x-filename"] || 'invoice.pdf';
}
// Determine the content type from the header or default to "application/octet-stream"
contentType = headers["content-type"] || octetStreamMime;
if (navigator.msSaveBlob) {
var blob = new Blob([data], { type: contentType });
navigator.msSaveBlob(blob, filename);
} else {
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (urlCreator) {
// Try to use a download link
var link = document.createElement("a");
if ("download" in link) {
// Prepare a blob URL
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
} else {
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
$window.location = url;
}
}
}
}).error(function (response) {
$log.debug(response);
});
Run Code Online (Sandbox Code Playgroud)
在我的服务器上,我使用Laravel,这是我的回答:
$headers = array(
'Content-Type' => $contentType,
'Content-Length' => strlen($data),
'Content-Disposition' => $contentDisposition
);
return Response::make($data, 200, $headers);
Run Code Online (Sandbox Code Playgroud)
这里$contentType是application/pdf和$contentDisposition是attachment; filename=" . basename($fileName) . '"'
$ filename - 例如 59005-57123123.PDF
我的回复标题:
Cache-Control:no-cache
Connection:Keep-Alive
Content-Disposition:attachment; filename="159005-57123123.PDF"
Content-Length:249403
Content-Type:application/pdf
Date:Mon, 25 Aug 2014 15:56:43 GMT
Keep-Alive:timeout=3, max=1
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?
根据屏幕截图,您似乎已将 Firefox 设置为在该计算机上打开 PDF 文档的默认应用程序。它使用嵌入式查看器来实现这一点。
因此它保存为 PDF,但您的打开应用程序首选项使其显示为 Firefox Html 文档。
如果您将打开方式首选项更改回 Adobe Reader,则另存为类型应在浏览器中正确显示。
我希望这有帮助。