这个代码Android和iOS都可以适用,代码中已经对iOS环境做了处理。这里的效果图,是以iOS为例进行展示的:
完整代码
页面代码:
<view style="margin: 10px;">
文件(点击可下载):
<view style="color: #1d7fff;" @click="downloadFile">
<u-icon name="download" style="margin-right: 8rpx;"></u-icon>测试文件
</view>
</view>
方法逻辑代码:
downloadFile() {
uni.downloadFile({
url: '你的请求地址',
header: {
'Content-Type': 'multipart/form-data;'
},
success: (data) => {
if (data.statusCode === 200) {
//隐藏加载框
uni.hideLoading();
//文件保存到本地
uni.saveFile({
tempFilePath: data.tempFilePath, //临时路径
success: function(res) {
// console.log('打印res',res)
uni.showToast({
icon: 'success',
mask: true,
// title: '文件已保存:' + res.savedFilePath, //保存路径
title: '保存成功',
duration: 2000,
});
//自动打开文档查看
setTimeout(() => {
var filePath = res.savedFilePath;
uni.openDocument({ //新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。
filePath: filePath,
showMenu: true,
success: function(res) {
console.log('打开文档成功');
},
fail: (e) => {
console.log(e, '打开失败')
let nowEno = uni.getSystemInfoSync().platform; //当前环境
// console.log('===========nowEno', nowEno)
if (nowEno == 'ios') { //ios打开临时路径文件失败 设置ios环境下读取临时路径文件可以打开
uni.getFileSystemManager().readFile({
filePath: filePath,
success: res => {
var filebuffer = res.data
return filebuffer
},
fail: err => {
console.log(err)
//图片
uni.saveImageToPhotosAlbum({
filePath: filePath,
success: res => {
uni.showToast({
title: "成功",
icon: "none"
});
},
fail: err => {
uni.showToast({
title: "失败,请稍后重试",
icon: "none"
});
}
});
}
})
} else {
uni.showToast({
title: '打开失败'
})
}
}
});
}, 2000)
}
});
}
},
fail: (err) => {
console.log(err);
uni.showToast({
icon: 'none',
mask: true,
title: '文件下载失败',
});
},
});
}