微信小程序上传图片

 chooseImg:function() {
    let that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      
      success: function (res) {
        console.log(res)
        var tempFilePaths = res.tempFilePaths
        that.data.urls = tempFilePaths[0] //图片地址

        that.setData({
          images: tempFilePaths[0],
          previewImage: that.data.urls
        })

        //启动上传等待中...
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })

        //上传图片
        wx.uploadFile({
          url: app.domain +'teacherapi/Course_Table/uploadImg', 
          filePath: tempFilePaths[0],
          name: 'file',
          header: {  "Content-Type": "multipart/form-data" },
          success:function(res){
            console.log(res)
            console.log(res.data)
            var data = JSON.parse(res.data)   //转换成json
            console.log(data)
            if(data.status == 0){
              // 上传成功
              wx.showToast({
                title: '上传成功',
                success:function(){
                  that.setData({
                    chooesImg: data.msg
                  }) 
                }
                
              })
            }else{
              wx.showToast({
                title: '上传失败',
                image: '/images/icon/daodi.png',
                duration: 1000
              })
              return;
            }
          },
          fail: function (res) {
            wx.hideToast();
            wx.showToast({
              title: '上传失败',
              image: '/images/icon/daodi.png',
              duration: 1000
            })
            return;
          }
        })
      }
    })
  },

wxml

<view class='prew_img' wx:if="{{chooesImg}}">
  <image src='{{previewImage}}' bindtap="previewImage"/>
</view>

 

posted @ 2018-11-27 12:10  下页、再停留  阅读(298)  评论(0编辑  收藏  举报