问题还原:
在项目开发中,用户上传完图片后,在展示区域想要预览图片,所以需要实现图片的在线预览功能。那么如何实现那?
解决方案:
**使用uni-app自带的uni.previewImage({current: 0, urls: url})即可实现图片的在线预览功能。**需要注意的是其中urls是图片路径数组。具体代码如下所示:
界面代码如下所示:
<text class="value"><a @tap="imgView(item.imgName, item.imgPath)" style="color: blue;">{{item.imgName}}</a></text>
JS代码如下所示:
methods: {
//图片预览
imgView(imgName, imgPath) {
if(imgName &&imgPath) {
const imgTypeArr = ["bmp","jpg","png","tif","gif","pcx","tga","exif","fpx","svg","psd","cdr","pcd","dxf","ufo","eps","ai","raw","WMF","webp","avif","apng"];
const lastIndex = imgName.lastIndexOf(".");
const imgType = imgName.substring(lastIndex + 1, imgName.length);
if(imgTypeArr.includes(imgType)) {
var imgPaths = [];
imgPaths.push(imgPath);//注:这里是图片的全路径,直接浏览器访问可以展示的那种。
uni.previewImage({
current: 0,
urls: imgPaths,//图片路径是个数组,数组里面放图片的全路径
longPressActions: { //长按保存图片到相册
itemList: ['保存图片'],
success: (data)=> {
uni.saveImageToPhotosAlbum({ //保存图片到相册
filePath: payUrl,
success: function () {
uni.showToast({icon:'success',title:'保存成功'})
},
fail: (err) => {
uni.showToast({icon:'none',title:'保存失败,请重新尝试'})
}
});
},
fail: (err)=> {
console.log(err.errMsg);
}
}
})
}else {
uni.showToast({
icon: 'none',
title: '只能预览图片!'
});
}
}
}
}
注:笔者在代码中判断了下文件格式是不是图片。
PS:欢迎大家点赞、关注、支持。如有需要,欢迎添加博主QQ沟通交流!QQ:156587607