这个破问题搞得我很难受,由于项目我是后来加入的,之前开发人员传入的filePath不是一个具体的文件地址,也不知什么原因导致下载不了也预览不了。
直接代码
let fileType = “PNG”;//文件类型
let filePath = "这里是需要下载的文件具体网络地址";
uni.showLoading({
title: '文件下载中'
});
if(fileType){
fileType = fileType.toLowerCase();
}
//先下载文件
uni.downloadFile({
url: encodeURI(filePath),//注意中文文件名的网络地址需要encodeURI
success(res) {
uni.hideLoading();
//预览图片或打开文件
if(fileType == "png" || fileType == "jpg" || fileType == "jpeg"){
// 图片的话直接预览
uni.previewImage({
urls: [res.tempFilePath]
});
uni.hideLoading();
}else{
uni.openDocument({
filePath: res.tempFilePath,
success() {
},
fail(e) {
uni.hideLoading();
uni.showToast({
icon: 'none',
title: '文件打开失败!'
});
}
});
}
},
fail() {
uni.hideLoading();
uni.showToast({
icon: 'none',
title: '下载出错!'
});
},
complete() {
uni.hideLoading();
}
});
最重要的这个还是要看 需要下载的文件地址是否存在。还有要具体的文件地址。必须是小程序已经设置名单的域名下的文件才行。