×

在微信小程序里上传图片

作者:jquery2018.08.09来源:Web前端之家浏览:17231评论:0
关键词:保存本地

在微信小程序里上传图片。

<!-- 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>

JS

//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)  放出来看,返回什么属性一目了然:
174529qybzhhdbgdbtb1mg.png

2、保存到本地

长按图片,保存到本地

<view>
  <view wx:if="{{tempFilePaths.length}}" >  
    <image wx:for="{{tempFilePaths}}" wx:key="{{key}}" src="{{item}}" bindlongpress='saveImg' data-name="{{item}}"></image>
  </view>
</view>

js

// 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) { 
            }
          })
        }      
      }
    })

  },
})

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/baocun434234234.html

网友评论文明上网理性发言 已有0人参与

发表评论: