小程序上传图片到七牛云存储,服务端使用nodejs的thinkjs框架
服务端
'use strict' import Base from './base.js'; import qiniu from 'qiniu'; export default class extends Base{ async uploadAction(){ var accessKey = '注册七牛云之后,七牛提供的accessKey'; var secretKey = '注册七牛云之后,七牛提供的secretKey'; var bucket = '你自己创建的存储对象' var mac = new qiniu.auth.digest.Mac(accessKey,secretKey); var options = { scope:bucket, }; var putPolicy = new qiniu.rs.PutPolicy(options); var uploadToken = putPolicy.uploadToken(mac); think.log(uploadToken) // 给前端返回一个uploadToken return this.success(uploadToken); } }
小程序端 通过服务端拿到uploadToken
upload: function () { var that = this; wx.request({ url: app.globalData.get_url + "/upload/upload", success: function (res) { var uploadToken = res.data.data; that.setData({ uploadToken: uploadToken }) } }) },
上传图片
chooseImage02: function (e) { var that = this; wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'],// 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { var wechatma = []; var tempFilePaths = res.tempFilePaths; var filePath = tempFilePaths[0]; //七牛提供的上传方法 qiniuUploader.upload(filePath, (res) => { wechatma.push(res.imageURL) that.setData({ imageURL02: res.imageURL, wechatma: wechatma }); }, (error) => { console.log('error: ' + error); }, { region: 'ECN', domain: app.globalData.upload_url + '/', uptoken: that.data.uploadToken, // 由其他程序生成七牛 uptoken }); } }) }, previewImage02: function (e) { wx.previewImage({ current: e.currentTarget.id, // 当前显示图片的http链接 urls: this.data.wechatma // 需要预览的图片http链接列表 }) },
效果如下: