小程序保存圖片功能實現
wxml:
<view class="previewImage" style="display:{{previewImage}}" bindtap="closePrev"> <image src="{{img.url}}" mode="aspectFit" style="width:100%;height:100%;" catchlongtap="saveImg"></image> </view> <action-sheet hidden="{{saveImage}}" bindchange="actionSheetChange"> <block> <action-sheet-item class="item" bindtap="downloadFile" data-image-href="{{img.url}}">保存圖片</action-sheet-item> </block> <action-sheet-cancel class="cancel">取消</action-sheet-cancel> </action-sheet>
wxss:
.previewImage{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; }
js:
previewImg:function(){ this.setData({ previewImage:"block" }); }, saveImg:function(){ longTouch = true; this.setData({ saveImage:false }) }, closePrev:function(){ if(longTouch){ longTouch = false; }else{ this.setData({ previewImage:"none" }); } }, actionSheetChange:function(){ this.setData({ saveImage:!this.data.saveImage }) }, downloadFile:function(e){ var imgUrl = e.currentTarget.dataset.imageHref; var that = this; wx.downloadFile({ url: imgUrl, type: 'image', success:function(res){ var tempFilePath = res.tempFilePath; console.log(tempFilePath); wx.saveFile({ tempFilePath:tempFilePath, success:function(res){ var savedFilePath = res.savedFilePath; console.log(savedFilePath); that.setData({ saveImage:true }); }, fail:function(res){ console.log(res); } }); }, fail:function(res){ console.log(res); } }); }