uniapp使用阿里oss上传

Posted on   矜持i  阅读(2087)  评论(0编辑  收藏  举报

可以删除重新上传,点击图片大图等功能。

复制代码
            <view class="uploadView">
                <view class="imageView" v-if="!imgShow">
                    <view class="upload_img_view">
                        <image src="../../../../static/img/SquareImg/shop_add.png" mode="" class="upload_img"
                            @click="uploadImg(['camera','album'])">
                        </image>
                    </view>
                    <view class="text">图片需大于600x450px,不超过3M</view>
                </view>
                <view class="imageView upload_view" v-else>
                    <view class="img_List" v-for="(item,index) in img" :key="index">
                        <image :src="item" mode="aspectFit" class="imgShow" @tap="refundPicPreView(item)"></image>
                        <image src="../../../../static/img/SquareImg/dyn_icon_del@3x.png" mode="" class="delete_icon"
                            @click="delImg(index)"></image>
                    </view>
                    <view class="upload_img_view">
                        <image src="../../../../static/img/SquareImg/shop_add.png" mode="" class="upload_img"
                            @click="uploadImg(['camera','album'])">
                        </image>
                    </view>
                    <view class="text">图片需大于600x450px,不超过3M</view>
                </view>
            </view>
复制代码

1、变量 引入import uploadImage from "../../../../js_sdk/yushijie-ossutil/ossutil/uploadFile"

        data() {
            return {
                imgShow: false, //图片上传控制
                img: [],
                image: [], //传给后台的图片集合
            }
        },

2、js methods

复制代码
            //上传图片
            uploadImg(sourceType) {
                const thisSelf = this;
                let oldImgsArr = thisSelf.img; //已上传的图片集合
                uni.chooseImage({
                    count: 9, // 默认最多一次选择9张图
                    sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
                    success: res => {
                        console.log('resss', res)
                        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
                        var tempFilePaths = res.tempFilePaths; //重新上传图片的集合
                        var newImgsArr = tempFilePaths.concat(oldImgsArr); //将已上传的图片集合与重新上传的图片集合拼接起来形成一个新的集合
                        thisSelf.img = newImgsArr; //这里的是展示在视图上的已上传图片的集合(已上传的+重新上传的)

                        var newArr = [];
                        var imgStr = '';
                        //支持多图上传
                        for (var i = 0; i < tempFilePaths.length; i++) {
                            //显示消息提示框
                            uni.showLoading({
                                title: '上传中...'
                            });

                            //上传图片
                            //图片路径可自行修改
                            uploadImage(tempFilePaths[i], 'picture/',
                                function(res) {
                                    uni.hideLoading();
                                    thisSelf.imgShow = true;
                                    newArr.push(res)
                                },
                                function(res) {
                                    //失败回调
                                }
                            )
                        }
                        setTimeout(() => {
                            let trueImgs = oldImgsArr.concat(newArr);
                            trueImgs.forEach(img => {
                                return imgStr += img + ',';
                            })
                            thisSelf.image = imgStr.substr(0, imgStr.length - 1); //这里是真实图片的集合 传此值给后台
                        }, 1000)
                    }
                })
            },
            //删除图片
            delImg(index) {
                this.img.splice(index, 1);
                if (this.img.length == 0) {
                    this.imgShow = false;
                    this.img = [];
                }
            },
            //图片预览
            refundPicPreView(imge) {
                var urls = []
                urls.push(imge)
                uni.previewImage({
                    current: urls[0],
                    urls: urls
                })
            },
复制代码

 

3、uploadFile.js代码

复制代码
const env = require('./config.js'); //配置文件,在这文件里配置你的OSS keyId和KeySecret,timeout:87600;

const base64 = require('./base64.js');//Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 
const uploadFile = function (filePath, dir, successc, failc) {
  if (!filePath || filePath.length < 9) {
    uni.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  
  //图片名字 可以自行定义,     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
  const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
  
  const aliyunServerURL = env.uploadImageUrl;//OSS地址,需要https
  const accessid = env.OSSAccessKeyId;
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64);//获取签名
 
  uni.uploadFile({
    url: aliyunServerURL,//开发者服务器 url
    filePath: filePath,//要上传文件资源的路径
    name: 'file',//必须填file
    formData: {
      'key': aliyunFileKey,
      'policy': policyBase64,
      'OSSAccessKeyId': accessid,
      'signature': signature,
      'success_action_status': '200',
    },
    success: function (res) {
            console.log(res);
      if (res.statusCode != 200) {
        failc(new Error('上传错误:' + JSON.stringify(res)))
        return;
      }
       successc(aliyunServerURL+aliyunFileKey);
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      failc(err);
    },
  })
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
    console.log(policyBase64);
  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);
console.log(signature);
  return signature;
}

module.exports = uploadFile;
复制代码

 

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了

随笔 - 10, 文章 - 0, 评论 - 0, 阅读 - 7868

Copyright © 2025 矜持i
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示