ali-oss web + 微信小程序 使用

2,194 阅读1分钟

记录一下看到大佬封装的ali-oss微信使用,和web使用

ali-oss的npm地址

https://www.npmjs.com/package/ali-oss
  • 微信小程序

代码地址

https://gitee.com/Ansxu/wxapp-ali-oss-use.git

需要更换alioss.js的accessKeyIdaccessKeySecret改成你的账号信息 在对应需要使用的页面引入alioss.js,然后use

import { uploadFile } from '../../utils/alioss.js';

// 上传头像
  upHeadImg() {
    const that = this;
    //选取头像
    wx.chooseImage({
      count: 1,
      success(e) {
        let image = e.tempFilePaths[0];
        uploadFile(image).then(function(res){
          if(res.status&& res.data.url){
              const info = that.data.info;
              info.headImg = res.data.url;
              that.setData({
                info
              });
          }else{
            console.log(res);
          }

        },function(res){
            console.log(res);
        });
      },
      fail(err){
        console.log(err);
      }
    })

  }
  • Web

//alioss.js
var OSS = require('ali-oss')

export function client() {
    //桶配置信息
  var client = new OSS({
    region: 'oss-cn-shenzhen',
    accessKeyId: 'LRAI*e9k1kpr**',
    accessKeySecret: 'iwGDzruu*Cj2FZ*PUhTqlF*NlLdraT',
    bucket: 'ali-oss-demo'
  })
  return client
}

直接更换ali-oss的accessKeyIdaccessKeySecret

put()接收两个参数,第一个为文件名称,第二个为上传的图片文件,详细参考开头给出链接

import { client } from '@/utils/alioss'
//上传图片
uploadImg(file) {
      const that = this
      var fileName = 'img' + file.file.uid
      client().put(fileName, file.file).then((result) => {
        that.row_data.img = result.url
        that.img = result.url
      }).catch((err) => {
        this.$message.error('图片上传失败,原因' + err)
      })
}

第二参数同input框的type="file"拿到的文件格式里的file属性值