一、获取文件流的两种方式
1、后端将附件转为base64传到前端,前端转换为文件流
2、后端提供服务器上存放的文件地址,前端通过设置响应的数据格式,获取到文件流
const xhr = new XMLHttpRequest();
xhr.open("GET", 文件地址, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
this.downloadAttach(xhr.response, item["fileName"]);
}
};
xhr.send();
二、在app侧下载打开
downloadAttach(DataBlob, filename) {
var folderpath = cordova.file.externalRootDirectory;//获取手机端存储文件的位置
window.resolveLocalFileSystemURL(folderpath, function (dir) {
let that = this;
console.log("Access to the directory granted succesfully");
dir.getFile(filename, { create: true }, function (file) {
console.log("File created succesfully.");
file.createWriter(
function (fileWriter) {
//写入结束
fileWriter.onwriteend = function () {
let finalPath = folderpath + filename;
console.log("写入文件成功,打开文件, filePath=" + finalPath);
//文件路径格式
// var basefileUrl = 'file:///storage/emulated/0/测试.docx';
navigator.appfilemanage.openFile(
function (value) {
//value 取值
/**
* 1 文件路径不存在
-1 参数错误
0 打开成功
*/
console.log("成功回调 :" + value);
},
function (msg) {
console.log("失败回调:" + msg);
},
finalPath
);
};
fileWriter.onerror = function (e) {
console.log("写入文件失败:" + e.toString());
};
console.log("Writing content to file");
fileWriter.write(DataBlob);
},
function () {
alert("Unable to save file in path " + folderpath);
}
);
});
});
},