1, 图片上传
- <!-- index.wxml-->
- <view>
- <button bindtap="uploadImg"> 上传图片 </button>
- <view wx:if="{{tempFilePaths.length}}">
- <image wx:for="{{tempFilePaths}}" wx:key="{{key}}" src="{{item}}"></image>
- </view>
- <view wx:if="{{uploadLinks.length}}">
- <image wx:for="{{uploadLinks}}" wx:key="{{key}}" src="{{item.path}}"></image>
- </view>
- </view>
- //index.js
- Page({
- data:{
- tempFilePaths:[],
- uploadLinks:[],
- },
- uploadImg() {
- var _this = this;
- wx.chooseImage({
- count: 9, // 默认 9
- sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图, 默认二者都有
- sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机, 默认二者都有
- success: function (res) {
- _this.setData({
- tempFilePaths: res.tempFilePaths, // 返回的 res.tempFilePaths 是数组
- uploadLinks: res.tempFiles // 返回的 res.tempFiles 是由多个对象组成的数组
- })
- }
- })
- }
- })
tempFilePaths,tempFiles 都是 res 的属性, 个人有个习惯, 喜欢把返回结果, 用 console.log(res) 放出来看, 返回什么属性一目了然:
2, 保存到本地
- <view>
- <view wx:if="{{tempFilePaths.length}}">
- <image wx:for="{{tempFilePaths}}" wx:key="{{key}}" src="{{item}}" bindlongpress='saveImg' data-name="{{item}}"></image>
- </view>
- </view>
- // pages/jump.js
- Page({
- data:{
- tempFilePaths:[]
- },
- uploadImg() {
- var _this = this;
- wx.chooseImage({
- count: 9, // 默认 9
- sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图, 默认二者都有
- sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机, 默认二者都有
- success: function (res) {
- console.log(res);
- _this.setData({
- tempFilePaths: res.tempFilePaths, // 返回的 res.tempFilePaths 是数组
- })
- }
- })
- },
- saveImg(e) {
- wx.showModal({ // 弹窗确认是否保存
- title: '保存图片?',
- success: function (res) {
- if (res.confirm) {
- wx.saveImageToPhotosAlbum({ // 保存图片
- filePath: e.currentTarget.dataset.name,
- success(res) {
- }
- })
- }
- }
- })
- },
- })
来源: http://www.qdfuns.com/article/25669/8384c8be8c8090bcd506bfff9a6dc86b.html