【发布时间】:2016-09-16 11:41:19
【问题描述】:
我使用 AngularJS 从网上获取 a 并将其存储在数据库中(我将其转换为字节数组)。 现在我想让使用 AngularJS 下载该文件成为可能。我该怎么做?(我必须将字节数组转换为其他格式吗?)文件扩展名可以是 pdf、doc/docx、jpg。
【问题讨论】:
我使用 AngularJS 从网上获取 a 并将其存储在数据库中(我将其转换为字节数组)。 现在我想让使用 AngularJS 下载该文件成为可能。我该怎么做?(我必须将字节数组转换为其他格式吗?)文件扩展名可以是 pdf、doc/docx、jpg。
【问题讨论】:
在您成功时执行此操作,否则会停止服务。
var a = document.createElement('a');
a.href = 'data:here goes the mime type of file,' + encodeURI(response);
a.target = '_blank';
a.download = 'file name . extension ';
document.body.appendChild(a);
a.click();
例如:我正在从 base64 字符串下载一个 csv 文件
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURI(response);
a.target = '_blank';
a.download = 'Export.csv';
document.body.appendChild(a);
a.click();
这里我是字符串 base64 响应
【讨论】:
这是我的 Angular 控制器
角度 .module('viewCvForm') .component('viewCvForm', {
templateUrl: 'view-cv-form/view-cv-form.template.html',
controller: ['$scope','$routeParams','Applicant',
function ApplicantController($scope,$routeParams,Applicant) {
console.log('Cv Controller');
console.log($routeParams.id);
var self=this;
fetchCV();
function fetchCV() {
var applicant={
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
jobId:0,
id:$routeParams.id
}
return Applicant.fetchCV(JSON.stringify(applicant))
.then(function (response) {
console.log(response);
var a = document.createElement('a');
a.href = 'data:application/txt,' + encodeURI(response.data);
a.target = '_blank';
a.download = 'cv.txt';
document.body.appendChild(a);
a.click();
d.resolve(response);
},
function (errResponse) {
console.error('Error while creating Interview');
}
);
}
}
]
});
response 是一个对象,它有一个名为“data”的字段,其类型为 byte[](在 Java 控制器中)。我使用此字段将文件保存到数据库中。 如何转换 response.data 以显示该文件中的内容,因为现在它只显示 base64 字符。
【讨论】:
这里是一个示例代码,用于在不同类型的浏览器中下载任何文件(例如:PDF)
$http.get("/displayPdf", {responseType: 'arraybuffer', params: {id: 1}}).success(function(data) {
var blob = new Blob([data], {type 'application/pdf'});
var anchor = document.createElement("a");
if(navigator.userAgent.indexOf("Chrome") != -1||navigator.userAgent.indexOf("Opera") != -1){
$window.open(URL.createObjectURL(file,{oneTimeOnly:true}));
}else if(navigator.userAgent.indexOf("iPad") != -1){
var fileURL = URL.createObjectURL(file);
//var anchor = document.createElement("a");
anchor.download="myPDF.pdf";
anchor.href = fileURL;
anchor.click();
}else if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1){
var url = window.URL.createObjectURL(file);
anchor.href = url;
anchor.download = "myPDF.pdf";
document.body.appendChild(anchor);
anchor.click();
setTimeout(function(){
document.body.removeChild(anchor);
window.URL.revokeObjectURL(url);
}, 1000);
}
});
【讨论】: