小程序上传文件到OSS

这里我是用的uniapp写的微信小程序

<view>
    <button @click='addPicture'>添加图片</button>
</view>

给一个按钮 点击上传图片

	import AliOss from "@/subPackages/utils/aliOssSts.js";
//这里我为了方便,写了两个数组 一个是用来展示的  一个是用来给后端的
fileList:[]        //展示
uploadList:[]      //上传给后端

//首先你要从你的后端获取token,要用这个token来向你的oss发出请求

//获取token
async getToken(){
   let res = await http({url:'你的url'})
   this.data = res
}

addPicture(){
    let that = this
	uni.chooseMessageFile({
        count:1,       //oss上传仅限一张
        sizeType: ["compressed", "camera"],
		sourceType: ["album", 'camera'],
        success(res){
        console.log(res)        //选择成功后 返回的结果
        if (res.tempFiles[0].path.slice(-4) == '.jpg' ||         
            res.tempFiles[0].path.slice(-4)=='.png') {
            that.fileList.push(res.tempFilePaths[0])    //图片展示列表push进去
            if (res.errMsg == "chooseImage:ok") {
             let filePath = res.tempFiles[0].path;
            let option = {                        //需要上传的参数
			savePath: "flies/aa/bb/cc",           //要上传的文件路径
			AccessKeySecret: that.data.accessKeySecret,
			SecurityToken: that.data.securityToken,
			AccessKeyId: that.data.accessKeyId,
			bucket: that.data.bucketName,
			area: that.data.regionId,
			};
//oss上传接口
AliOss.upload(filePath,option,function (res){
//返回给你的是oss上传后的路径,把他放到你将要给后端的数组里,如果后端需要你处理,就要处理一下
    console.log(res)       
    that.uploadList.push(res)
})
}
}
}
})
}
//这里我没有写fail的回调,大家有需求的话,自己加上就好

删除图片:

    //v-for展示图片  在点击删除时,带上index参数 然后splice删除即可
removePicture(index){
    this.uploadList.splice(index,1)
    this.fileList.splice(index,1)
}

aliOssSts.js

//这里是摘拿其他佬的,忘了具体是哪位佬了  如果侵犯,,请联系删除,无意冒犯。

这里需要 npm crypto-js


 import crypto from '../node_modules/crypto-js';
 import {
     Base64
 } from '../node_modules/js-base64';

 function upload(filePath, option = {
     savePath,
     AccessKeySecret,
     SecurityToken,
     AccessKeyId,
     bucket,
     area
 }, callBack = () => {}) {
     let fileType = filePath.split(".").pop();
     let filename = option.savePath + "/" + createFileName(32) + "." + fileType;


     const date = new Date();
     date.setHours(date.getHours() + 1);
     const policyText = {
         expiration: date.toISOString(), // 设置policy过期时间。
         conditions: [
             ["content-length-range", 0, 1024 * 1024 * 1024],
         ],
     };
     const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
     const signature = computeSignature(option.AccessKeySecret, policy)
     const formData = {
         OSSAccessKeyId: option.AccessKeyId,
         signature,
         policy,
         'x-oss-security-token': option.SecurityToken,
         key: filename,
         success_action_status: 200
     }

     uni.uploadFile({
         url: "https://" + option.bucket +
             "." + option.area + ".aliyuncs.com",
         filePath: filePath,
         name: "file",
         formData: formData,
         success: (res) => {
			 console.log("https://" + option.bucket +
             "." + option.area + ".aliyuncs.com",);
             let ossFileName = false;
             if (res.statusCode === 200) {
                 console.log('上传成功');
                 ossFileName = "https://" + option.bucket +
                     "." + option.area + ".aliyuncs.com/" +
                     filename;
             }
             callBack(ossFileName);
         },
         fail: err => {
             console.log(err);
             callBack(false);
         }
     })
 }




 // 签名
 function computeSignature(accessKeySecret, canonicalString) {
     return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
 }

 // 生成随机文件名
 function createFileName(length) {
     const data = [
         "0",
         "1",
         "2",
         "3",
         "4",
         "5",
         "6",
         "7",
         "8",
         "9",
         "A",
         "B",
         "C",
         "D",
         "E",
         "F",
         "G",
         "H",
         "I",
         "J",
         "K",
         "L",
         "M",
         "N",
         "O",
         "P",
         "Q",
         "R",
         "S",
         "T",
         "U",
         "V",
         "W",
         "X",
         "Y",
         "Z",
         "a",
         "b",
         "c",
         "d",
         "e",
         "f",
         "g",
         "h",
         "i",
         "j",
         "k",
         "l",
         "m",
         "n",
         "o",
         "p",
         "q",
         "r",
         "s",
         "t",
         "u",
         "v",
         "w",
         "x",
         "y",
         "z",
     ];
     let nums = "";
     for (let i = 0; i < length; i++) {
         const r = parseInt(Math.random() * 61, 10);
         nums += data[r];
     }
     return nums;
 }




 export default {
     upload
 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值