我想知道如何以角度保存服务器响应中包含的文件? (这样当响应到达时会自动下载文件)
编辑:
我有一个$ http post方法,我在响应中得到了pdf数据。成功后,我想将响应数据保存为pdf文件。
电子。 g:
$http({
method: 'POST',
url : 'theUrl',
data: //some array that is received
headers : //content type info
}
.success(function(response) { // I want to save the response as a pdf });
答案 0 :(得分:3)
使用HTML5 FileSaver界面,可以实现:
https://github.com/eligrey/FileSaver.js/
示例解决方案:
//Call API to retrieve file stream using POST request
$http.post("URL", searchData, { responseType: 'arraybuffer' }).then(
response => {
//Download file from response
saveFileAs(response);
},
data => {
//raise error
}
);
function saveFileAs(response) {
var contentDisposition = response.headers("content-disposition");
//Retrieve file name from content-disposition
var fileName = contentDisposition.substr(contentDisposition.indexOf("filename=") + 9);
fileName = fileName.replace(/\"/g, "");
var contentType = response.headers("content-type");
var blob = new Blob([response.data], { type: contentType });
saveAs(blob, fileName);
}
答案 1 :(得分:2)
在角度2上......你可以这样做:
import { saveAs } from 'browser-filesaver/FileSaver.js'
downloadFile(data: Response) {
var blob = new Blob([data], {type: 'application/x-tar'});
saveAs(blob, "report.tgz");
}
答案 2 :(得分:1)
由于您无法在浏览器中访问用户文件系统,因此无法保存文档。您可以发回pdf的URL,然后通过向正文添加虚拟iFrame来触发浏览器内置文件保存/打开机制:
$http({
method: 'POST',
url : 'theUrl',
data: //some array that is received
headers : //content type info
}
.success(function (data) {
if ($('#iframe').length == 0) {
var $iframe = $('<iframe id="iframe" style="display: none"></iframe>');
$('body').append($iframe);
}
$('#iframe').attr('src', {{url to retrieve the file}})
})