1. 程式人生 > 其它 >uniapp使用阿里oss上傳

uniapp使用阿里oss上傳

可以刪除重新上傳,點選圖片大圖等功能。

            <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/[email protected]" 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;