【发布时间】:2014-08-25 16:07:40
【问题描述】:
我想使用$http 从网络服务器下载一个 pdf 文件。我使用这段代码效果很好,我的文件只保存为 html 文件,但是当我打开它时,它以 pdf 格式打开,但在浏览器中打开。我在 Chrome 36、Firefox 31 和 Opera 23 上对其进行了测试。
这是我的 angularjs 代码 (based on this code):
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);
});
在我的服务器上,我使用 Laravel,这是我的回应:
$headers = array(
'Content-Type' => $contentType,
'Content-Length' => strlen($data),
'Content-Disposition' => $contentDisposition
);
return Response::make($data, 200, $headers);
其中$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
我做错了什么?
【问题讨论】:
-
你能在设置文件名的地方加上
console.log(filename),并确认它是invoice.pdf。并确认在控制台中输入document.createElement("a")不会返回undefined -
文件名是 159005-57123123.PDF 并且链接不是未定义的。
-
删除添加到代码中的
$window.saveAs(blob, filename); return;会发生什么。 -
哦,对不起,这是我的错误,我在尝试其他解决方案时忘记删除它,但问题仍然存在。
-
能否添加出现的另存为对话框的截图?
标签: javascript angularjs