微信小程序---多图上传到七牛,并从七牛传到服务器(多图上传和重命名)

实现本地图片上传--->七牛---->服务器

微信小程序---多图上传到七牛,并从七牛传到服务器(多图上传和重命名)

1.调取图片上传wx.chooseImage({})

2.将上传的图片拼接成数组,并重命名

3. 上传至七牛,成功后返回key值,拼接成字符串后

  • 在 SDK 目录下找到 qiniuUploader.js 文件,在需要使用上传功能的页面引用 qiniuUploader.js 文件, 该方法四个参数,上传成功的回调函数返回了成功上传图片的链接

  • 获取七牛直传的token,调取后台接口文档七牛模块的前端使用接口,获取token和域名

  • 图片路径数组

  • 图片命名数组

4.上传至服务器

务必引入七牛的js:

var qiniuUploader = require('../../script/qiniuUploader.js');

第一步:index.wxml:

  <view class="gallery">
    <view class="item" wx:for="{{images}}" wx:key="index">
      <image src="{{item}}" data-src="{{item}}" bindtap="previewImage" mode="aspectFit" />
      <!-- 删除按钮 -->
      <view class="delete" bindtap="delete" data-index="{{index}}">
        <image src='../image/delete.png' mode="widthFix"></image>
      </view>
    </view>
    <view class="item2" bindtap="chooseImage">
      <view class='addIcon'><image src='../image/add.png'></image></view>
    </view>
  </view>
  <view class='codeSubmit'>
      <view bindtap="uploadImgSubmit" class='btn'>确认上传</view>
  </view>

第二步:index.wxss:

.item {
  position: relative;
  margin: 10rpx 2%;
  width: 46%;
  height: 442rpx;
  background: #f3f3f3;
}
.item image {
  width: 100%;
  height: 100%;
}
/*add按钮*/
.item2 {
  margin: 10rpx 2%;
  width: 45%;
  height: 442rpx;
  text-align: center;
  line-height: 442rpx;
  font-size: 200rpx;
  background: #fff;
  color: #e4e5ea;
  border: 1px dashed #e4e5ea;
}
.addIcon image{
  width: 110rpx;
  height: 110rpx;
}
/*删除按钮*/
.delete {
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 80rpx;
  font-size: 22rpx;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.3);
  display: none;
}
.delete image {
  width: 44rpx;
  margin-top: 22rpx;
}
/*确认提交按钮*/
.codeSubmit {
  font-size: 30rpx;
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  margin: 0 auto;
  text-align: center;
  padding: 50rpx 0 80rpx 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.codeSubmit .btn {
  width: 300rpx;
  text-align: center;
  border-radius: 120rpx;
  background: #000;
  color: #d1b75e;
}

index.js:

(1)本地上传图片:bindtap="previewImage"

Page({
  data: {
    images: [],
    pathsTmp: [],
  },  
// 本地选择照片上传
  chooseImage: function() {
    var that = this
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
          //文件重命名并拼接数组--目的是上传七牛
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          var suiji = Math.floor(Math.random() * 100000)
          var year = new Date().getFullYear();
          var month = new Date().getMonth() + 1;
          var day = new Date().getDate();
          var path = year + '/' + month + '/' + day + '/' + suiji + '.jpg';
          that.data.pathsTmp = that.data.pathsTmp.concat(path)
        }
        //打印文件名称
        console.log(that.data.pathsTmp)
        that.setData({
          //将上传的图片拼接成数组--目的是批量上传至七牛
          images: that.data.images.concat(res.tempFilePaths)
        });
        //打印上传图片的数组
        console.log(that.data.images)
      }
    })
  },
})

(2)确认提交:bindtap="uploadImgSubmit"

  // 确定打印
  uploadImgSubmit: function() {
    var that = this;
    if (that.data.images.length == 0) {
      wx.showToast({
        title: '请上传手机照片',
        image: '../../image/error.png',
        duration: 1500
      })
    } else {
      //上传图片到七牛
      //将图片地址和图片命名传入
      that.pictureUploadqiniuMethod(that.data.pathsTmp, that.data.images)
    }
  },

(3)上传七牛方法:

Page({
  data: {
    imgList: []
  },
  onLoad: function(options) {
    var that = this
    // 获取token
    wx.request({
        url: 'https://xxxx/upToken',
        method: "GET",
        header: {
          'Content-Type': 'application/json'
        },
        success: res => {
          this.setData({
            uploadToken: res.data.result.upToken
          })
        }
      }),
  },
//得到图片路径数组后,准备上传七牛
  //fileHead文件命名,imageArray文件数组
  pictureUploadqiniuMethod: function(fileHead, imageArray) {
    var that = this;
    for (var i = 0; i < imageArray.length; i++) {
      var filePath = imageArray[i];  
      qiniuUploader.upload(filePath, (res) => {
        //上传成功,上传成功一张图片,进入一次这个方法,也就是返回一次
        //七牛上传成功重新组成数组imgList
          that.setData({
            imgList: that.data.imgList.concat(res.key),
          });
          console.log("imgList:" + that.data.imgList)
          console.log("qn:" + that.data.imgList.length)
          console.log("qn:" + imageArray.length)
          //检测是否上传完毕(本地上传的图片长度===上传七牛成功的图片长度)
          if (imageArray.length === that.data.imgList.length) {
             // 第三步:上传服务器
             that.uploadserver();
             console.log('七牛上传完毕')
           }
        },
        (error) => {
          //图片上传失败,可以在七牛的js里面自己加了一个err错误的返回值
          console.log('error: ' + error)
        },
        {
          uploadURL: 'https://upload-z1.qiniup.com', //华北
          domain: 'https://xxx.cn/',//图片地址
          region: 'NCN',
          key: fileHead[i],//图片命名
          uptoken: that.data.uploadToken,//在onLoad中执行获取uploadToken
          uptokenURL: 'https://xxx/upToken',//获取upToken的url
        });
    }
  },
})

七牛返回的res参数:

微信小程序---多图上传到七牛,并从七牛传到服务器(多图上传和重命名)

 (4)上传服务器的方法:

  // 将图片上传至服务器
  uploadserver: function() {
    var that = this;
    console.log("将图片上传至服务器")
    //将数组转为字符串
    var printphoto = that.data.imgList
    var printphoto2 = printphoto.toString(',');
    console.log(printphoto2)
    wx.request({
      url: 'https://xxx/localPrint/uploadImage',
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'GET',
      data: {
        images: printphoto2
      },
      success: function(res) {
        console.log("将图片上传至服务器")
      }
    })
  },

(5)删除图片

  // 删除照片
  delete: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var images = that.data.images;
    images.splice(index, 1);
    //图片命名数组
    var pathsTmp = that.data.pathsTmp;
    pathsTmp.splice(index, 1);
    that.setData({
      images: images,
      pathsTmp: pathsTmp
    });
    console.log(that.data.images)
    console.log(that.data.pathsTmp)
  },

这样就成功上传到服务器了。本地图片上传--->七牛---->服务器

微信小程序---多图上传到七牛,并从七牛传到服务器(多图上传和重命名)