我想使用
这是我的AngularJS代码(基于此代码):
在我的服务器上,我使用Laravel框架,以下是我的响应:
$http
从Web服务器下载PDF文件。我使用了下面这段代码,它可以正常工作,但我的文件只能保存为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);
});
在我的服务器上,我使用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
What am I doing wrong?
console.log(filename)
并确认它是invoice.pdf
。还要确认在控制台中输入document.createElement("a")
不会返回undefined
。 - Scott$window.saveAs(blob, filename); return;
时会发生什么? - Scott