提示:本人親測(cè)可直接使用
一、封裝下載js文件 download.js?
const app = getApp()
export default {
/**
* 保存圖片
* url 圖片url地址
* is_video是否視頻
*/
saveImage: function(url,is_video) {
let that = this;
// 向用戶發(fā)起授權(quán)請(qǐng)求
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
// 已授權(quán)
that.downLoadImg(url,is_video);
},
fail: () => {
// 拒絕授權(quán),獲取當(dāng)前設(shè)置
uni.getSetting({
success: (result) => {
if (!result.authSetting['scope.writePhotosAlbum']) {
that.isAuth()
}
}
});
}
})
},
/**
* 下載資源,保存圖片到系統(tǒng)相冊(cè)
*/
downLoadImg: function(url,is_video) {
uni.showLoading({
title: '加載中'
});
uni.downloadFile({
url : url,
success: (res) => {
uni.hideLoading();
if (res.statusCode === 200) {
if(is_video==false){
// 圖片下載
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "已保存到相冊(cè)",
icon: "none"
});
},
fail: function() {
uni.showToast({
title: "保存失敗,請(qǐng)稍后重試",
icon: "none"
});
}
});
}else{
// 視頻下載
uni.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "已保存到相冊(cè)",
icon: "none"
});
},
fail: function() {
uni.showToast({
title: "保存失敗,請(qǐng)稍后重試",
icon: "none"
});
}
})
}
}else {
uni.showToast({title:"資源格式錯(cuò)誤,請(qǐng)聯(lián)系管理員",icon: "none"});
}
},
fail: (err) => {
uni.showToast({title: "保存失敗,請(qǐng)聯(lián)系管理員",icon: "none"});
}
})
},
/*
* 引導(dǎo)用戶開(kāi)啟權(quán)限
*/
isAuth: function() {
uni.showModal({
content: '由于您還沒(méi)有允許保存圖片到您相冊(cè)里,無(wú)法進(jìn)行保存,請(qǐng)點(diǎn)擊確定允許授權(quán)',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: (result) => {
console.log(result.authSetting);
}
});
}
}
});
},
}
二、使用
1.在 main.js引用
import imgDown from "./utils/download.js"
Vue.prototype.$imgDown = imgDown
2.頁(yè)面使用
url: http 圖片/視頻
is_video:false圖片下載 true視頻下載
this.$imgDown.saveImage(url,is_video)
總結(jié)
提示:這是使用的小程序,可以去體驗(yàn)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-515253.html
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-515253.html
到了這里,關(guān)于使用uniapp實(shí)現(xiàn)小程序圖片和視頻的下載功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!