从Blob中的服务器转换返回的文件并下载 [英] Convert returned file from server in blob and download
本文介绍了从Blob中的服务器转换返回的文件并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试隐藏Blob中服务器返回的文件并下载它,但我缺少smth.文件类型可以是图片,pdf或doc.
I am trying to covert returned file from server in blob and download it but I am missing smth. file type could be image, pdf or doc.
这是文件响应的样子
$http.get('url', {
headers: {'Content-Type': undefined}
}).then(function (response) {
var blob = new Blob([response.data], { type: 'image' }),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
}).catch(function(error) {
});
我在做什么错,这不能按预期工作?
what am I doing wrong and this does not work as expected ?
推荐答案
-
首先将blob转换为base64格式
First convert blob to base64 format
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data);
}
然后使用base64下载文件
Then use the base64 to download the file
downloadFile(base64data, type, fileName) {
const file = window.btoa(base64data);
const url = `data:${fileType};base64,` + file;
let a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
这篇关于从Blob中的服务器转换返回的文件并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文