当前位置: 首页 > news >正文

小程序上传图片到七牛云(支持多张上传,预览,删除)

以下为wxml (使用的vant小程序ui框架,需在json文件里自行引入)

<view class='clearFloat'>
    <view class='upload_title'>头像展示(必填)
      <span class="basic_title_desc">(选一张好看的个人照片可以增加客户点击的机会哦)
      </span>
    </view>
    <view class='healthCertImg'>
      <view class='imgrelative' wx:if="{{headIconArr}}" wx:for="{{headIconArr}}" wx:for-index="index" wx:for-item="item" wx:key="*this">
        <image class="image uploadimg" src="{{imgPath+item.key}}" mode="aspectFit" id="{{imgPath+item.key}}" catchtap='previewHeadIcon'>{{item}}</image>
        <van-icon name="clear" custom-style="color:#979797;position:absolute;right:-20rpx;top:-20rpx;" id="{{index}}" bind:click="deleteHeadIcon" />
      </view>
      <image src='../../imgs/upload.png' class='uploadimg upload_jkz' catchtap='headIcon' wx:if="{{IsHeadIcon}}"></image>
    </view>
  </view>

以下为wxss

.clearFloat {
  clear: both;
  overflow: hidden;
}
.upload_title {
  color: #222;
  font-size: 32rpx;
  margin-bottom: 16rpx;
  display: block;
  margin-top: 50rpx;
}
.imgrelative {
  position: relative;
  height: 164rpx;
  width: 164rpx;
  margin-right: 43rpx;
  float: left;
}
.uploadimg {
  height: 164rpx;
  width: 164rpx;
  float: left;
}

以下为json

{
  "usingComponents": {
    "van-popup": "../../vant/popup/index",
    "van-area": "../../vant/area/index",
    "van-icon": "../../vant/icon/index",
    "van-toast": "../../vant/toast/index",
    "van-datetime-picker": "../../vant/datetime-picker/index",
    "van-field": "../../vant/field/index",
    "upload": "../../component/upload/index"
  }
}

以下为js文件(涉及到封装的微信ajax和七牛云上传图片方法在下面)

const util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader");
   
// 头像展示上传图片
  headIcon() {
    var that = this
    that.chooesImage(that, 1, function(res) {
      that.data.headIconArr.push(res)
      // console.log(that.data.ysCertImgArr.length)
      if (that.data.headIconArr.length >= 1) {
        that.setData({
          IsHeadIcon: false
        });
      }
      that.setData({
        headIconArr: that.data.headIconArr
      });
    })
  },
 // 头像展示预览与删除
  previewHeadIcon(e) {
    this._previewImage(e, this.data.headIconArr)
  },
  deleteHeadIcon(e) {
    var that = this
    that._deleteImage(e, that.data.headIconArr, function(files) {
      that.setData({
        headIconArr: files,
        IsHeadIcon: true
      });
    })
  },

 /*图片上传*/
  chooesImage(that, count, callback) {
    util.didPressChooesImage(that, count, function(filePath) {
      qiniuUploader.upload(filePath, (res) => {
          console.log(res)
          callback(res)
          that.checkSubmit()
        }, (error) => {
          console.error('error: ' + JSON.stringify(error));
        },
        null, // 可以使用上述参数,或者使用 null 作为参数占位符
        (progress) => {
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
        }, cancelTask => that.setData({
          cancelTask
        })
      );
    })
  },
/*图片预览*/
  _previewImage: function(e, arr) {
    var preUlrs = [];
    console.log(arr)
    const imgPath = 'https://cdn.wutongdaojia.com/'
    arr.map(
      function(value, index) {
        var key = imgPath + value.key
        preUlrs.push(key);
      }
    );
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: preUlrs // 需要预览的图片http链接列表
    })
  },
  /*图片删除*/
  _deleteImage: function(e, arr, callback) {
    var that = this;
    var files = arr;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    console.log(index)
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗?',
      success: function(res) {
        if (res.confirm) {
          files.splice(index, 1);
          console.log(files)
        } else if (res.cancel) {
          return false;
        }
        // files,
        that.setData({
          isCanAddFile: true
        });
        that.checkSubmit()
        callback(files)
      }
    })
  },

以下为封装的七牛云上传图片方法(util.js)

const qiniuUploader = require("./qiniuUploader");
import api from './api.js';

const getUploadToken = () => {
  var params = {
    token: wx.getStorageSync('token')
  }
  api.ajax("GET", params, "/weixin/getUploadToken").then(res => {
    console.log(res.data)
    initQiniu(res.data)
  });
}
// 初始化七牛相关参数
const initQiniu = (uptoken) => {
  var options = {
    region: 'NCN', // 华北区
    // uptokenURL: 'https://[yourserver.com]/api/uptoken',
    // cdn.wutongdaojia.com
    // uptokenURL: 'http://upload-z1.qiniup.com',
    // uptokenURL: 'https://yuesao.wutongdaojia.com/weixin/getUploadToken',
    // uptoken: 'xxx',
    uptoken: uptoken,
    // domain: 'http://[yourBucketId].bkt.clouddn.com',
    domain: 'space.bkt.clouddn.com',  // space为七牛云后台创建的空间
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

export function didPressChooesImage(that, count, callback) {
  getUploadToken();
  // 微信 API 选文件
  wx.chooseImage({
    count: count,
    success: function(res) {
      console.log(res)
      var filePath = res.tempFilePaths[0];
      console.log(filePath)
      callback(filePath)
      // 交给七牛上传
    }
  })
}

/**
 * 文件上传
 * 服务器端上传:http(s)://up.qiniup.com
 * 客户端上传: http(s)://upload.qiniup.com
 * cdn.wutongdaojia.com
 */
function uploader(file, callback) {
  initQiniu();
  qiniuUploader.upload(filePath, (res) => {
      // 每个文件上传成功后,处理相关的事情
      // 其中 info 是文件上传成功后,服务端返回的json,形式如
      // {
      //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
      //    "key": "gogopher.jpg"
      //  }
      // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
      that.setData({
        'imageURL': res.imageURL,
      });
    }, (error) => {
      console.log('error: ' + error);
    },
    // , {
    //     region: 'NCN', // 华北区
    //     uptokenURL: 'https://[yourserver.com]/api/uptoken',
    //     domain: 'http://[yourBucketId].bkt.clouddn.com',
    //     shouldUseQiniuFileName: false
    //     key: 'testKeyNameLSAKDKASJDHKAS'
    //     uptokenURL: 'myServer.com/api/uptoken'
    // }
    null, // 可以使用上述参数,或者使用 null 作为参数占位符
    (res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    });
};
module.exports = {
  initQiniu: initQiniu,
  getUploadToken: getUploadToken,
  didPressChooesImage: didPressChooesImage
}

封装小程序wx.request(api.js)

const ajax = (Type, params, url) => {
  var methonType = "application/json";
  // var https = "http://www.wutongdaojia.com"
  var https = "https://yuesao.wutongdaojia.com"
  var st = new Date().getTime()
  if (Type == "POST") {
    methonType = "application/x-www-form-urlencoded"
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: https + url,
      method: Type,
      data: params,
      header: {
        'content-type': methonType,
        'Muses-Timestamp': st,
        'version': 'v1.0' // 版本号
        // 'Muses-Signature': sign
      },
      success: function (res) {
        // if (res.statusCode != 200) {
        //   reject({ error: '服务器忙,请稍后重试', code: 500 });
        //   return;
        // }
        // resolve(res.data);
        wx.hideLoading()
        console.log(res)
        if (res.data.status == 200) {
          resolve(res.data);
        } else if (res.data.status == 400) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000
          })
          return
        } else if (res.data.status == 401){
          wx.removeStorageSync('phone')
          wx.removeStorageSync('token')
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000,
            success:function(){
              wx.navigateTo({
                url: '../login/index',
              })
            }
          })
          return
        } else {
          //错误信息处理
          wx.showToast({
            title: '服务器错误,请联系客服',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ error: '网络错误', code: 0 });
      },
      complete: function (res) {
        // complete
      }
    })
  })
}

有什么不懂的可以加我微信(18310911617)
备注(说明来意)


相关文章:

  • 动态魔术使用DBMS_SQL
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • 接力10G,25G将成为数据中心首选解决方案
  • Redash本地开发环境搭建
  • 基于MaxCompute打造轻盈的人人车移动端数据平台
  • Chrome 被曝 0day 漏洞,可让黑客获取用户数据
  • Linux权限管理(week1_day5)--技术流ken
  • 基于ArcFace2.0+红外双目摄像头的活体检测 [Windows][C#][.NET][WPF]
  • Android 架构优化~MVP 架构改造
  • python列表,字典,集合
  • 关于移动端页面在手机调整字体大小后无法正常显示(已解决)
  • 一位90后的自述:如何从年薪3w到30w
  • POJ 2594 Treasure Exploration(最小可相交路径覆盖)题解
  • Docker下部署自己的LNMP工作环境
  • 移动APP安全测试
  • ES6指北【2】—— 箭头函数
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • 《网管员必读——网络组建》(第2版)电子课件下载
  • Android交互
  • Git的一些常用操作
  • HTML-表单
  • Java新版本的开发已正式进入轨道,版本号18.3
  • JS+CSS实现数字滚动
  • JS创建对象模式及其对象原型链探究(一):Object模式
  • php中curl和soap方式请求服务超时问题
  • Selenium实战教程系列(二)---元素定位
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • vue-loader 源码解析系列之 selector
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • win10下安装mysql5.7
  • 猴子数据域名防封接口降低小说被封的风险
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • 每天10道Java面试题,跟我走,offer有!
  • 如何在 Tornado 中实现 Middleware
  • 如何正确配置 Ubuntu 14.04 服务器?
  • 小试R空间处理新库sf
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • 宾利慕尚创始人典藏版国内首秀,2025年前实现全系车型电动化 | 2019上海车展 ...
  • 测评:对于写作的人来说,Markdown是你最好的朋友 ...
  • #单片机(TB6600驱动42步进电机)
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (007)XHTML文档之标题——h1~h6
  • (02)Hive SQL编译成MapReduce任务的过程
  • (04)Hive的相关概念——order by 、sort by、distribute by 、cluster by
  • (LeetCode 49)Anagrams
  • (八)c52学习之旅-中断实验
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (二)换源+apt-get基础配置+搜狗拼音
  • (生成器)yield与(迭代器)generator
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (转)ObjectiveC 深浅拷贝学习
  • (转)为C# Windows服务添加安装程序
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler
  • .NET/C# 中设置当发生某个特定异常时进入断点(不借助 Visual Studio 的纯代码实现)