2018/6/21 20:56:26当前位置推荐好文阿里云教程浏览文章

效果图:


效果图

一.准备工作

1.登录阿里云服务器配置需要的参数AccessKeySecret和OSSAccessKeyId。

var fileHost = "http://.oss-cn-qingdao.aliyuncs.com/"var config = {  //aliyun OSS config  uploadImageUrl: `${fileHost}`, //默认存在根目录,可根据需求改  AccessKeySecret: xgZVY4DHfBnlmwGlsWivF,  OSSAccessKeyId: XfOiw9ucL,  timeout: 87600 //这个是上传文件时Policy的失效时间};module.exports = config

2.Base64,hmac,sha1,crypto相关算法签名算法去下载

3.WeUI组件上传图片(用方法请参考https://www.jianshu.com/p/010cea4202b8)

4.上传图片主要的代码为:
uploadAliyun.js

const env = require(./config.js);const Base64 = require(./Base64.js);require(./hmac.js);require(./sha1.js);const Crypto = require(./crypto.js);const uploadFile = function (params) {  if (!params.filePath || params.filePath.length < 9) {    wx.showModal({      title: 图片错误,      content: 请重试,      showCancel: false,    })    return;  }  const aliyunFileKey = params.dir + params.filePath.replace(wxfile://, );  const aliyunServerURL = env.uploadImageUrl;  const accessid = env.OSSAccessKeyId;  const policyBase64 = getPolicyBase64();  const signature = getSignature(policyBase64);  console.log(aliyunFileKey=, aliyunFileKey);  console.log(aliyunServerURL, aliyunServerURL);  wx.uploadFile({    url: aliyunServerURL,    filePath: params.filePath,    name: file,    formData: {      //name: "picture.png",      key: aliyunFileKey,      policy: policyBase64,      OSSAccessKeyId: accessid,      signature: signature,      success_action_status: 200,    },    success: function (res) {      if (res.statusCode != 200) {        if (params.fail) {          params.fail(res)        }        return;      }      if (params.success) {        params.success(aliyunFileKey);      }    },    fail: function (err) {      err.wxaddinfo = aliyunServerURL;      if (params.fail) {        params.fail(err)      }    },  })}const getPolicyBase64 = function () {  let date = new Date();  date.setHours(date.getHours() + env.timeout);  let srcT = date.toISOString();  const policyText = {    "expiration": srcT, //设置该Policy的失效时间    "conditions": [      ["content-length-range", 0, 5  1024  1024] // 设置上传文件的大小限制,5mb    ]  };  const policyBase64 = Base64.encode(JSON.stringify(policyText));  return policyBase64;}const getSignature = function (policyBase64) {  const accesskey = env.AccessKeySecret;  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {    asBytes: true  });  const signature = Crypto.util.bytesToBase64(bytes);  return signature;}module.exports = uploadFile;

注意:在小程序的配置位置如图:


项目中js的位置

5.选图片的方法:

chooseImage:function(e){    var selectPictureNum = e.target.dataset.num;    this.setData({      count: 9 - selectPictureNum    })    var that = this;    wx.chooseImage({      count: that.data.count, // 默认9      sizeType: [original, compressed], // 能指定是原图还是压缩图,默认二者都有      sourceType: [album, camera], // 能指定来源是相册还是相机,默认二者都有      success: function(res) {        var tempFilePaths = res.tempFilePaths;        that.setData({          filePath: res.tempFilePaths[0],          images: that.data.images.concat(tempFilePaths)        })      },    })  },

点击确定上传到的代码(多张图片):

uploadImg: function(){    var that = this;    console.log(JSON.stringify(that.data.uploadImgs))    for (var i = 0; i < that.data.uploadImgs.length;i++){      var filePath = that.data.uploadImgs[i];      uploadImage(        {          filePath: filePath,          dir: "images/",          success: function (res) {            console.log("上传成功")            console.log("上传成功" + JSON.stringify(res))          },          fail: function (res) {            console.log("上传失败")            console.log(res)          }        })    }      },

uploadImg.wxss代码:

@import "../../weui.wxss"; 

6.上传成功后的结果如图:


结果

其中

images/http://tmp/wx1b4e5e756cd48af1.o6zAJsws4grEQvYrWTjBigy-6QaU.0llhudiKSF2V955a1c48350d9328ef064b4d36d12746.jpg

就是在阿里云服务器的图片名称,拼接上"http://yijiao.oss-cn-qingdao.aliyuncs.com/images/http://tmp/wx1b4e5e756cd48af1.o6zAJsws4grEQvYrWTjBigy-6QaU.0llhudiKSF2V955a1c48350d9328ef064b4d36d12746.jpg"才是完整图片。

该demo gitHub的下载地址: dt8888/uploadImage,如有疑问请发简信给我,定会回复。

网友评论