oss文件,oss.js

import Vue from 'vue';
let vm = new Vue();
//请求后台获取oss签名信息
function httpGetOssInfo() {
    return vm.$u.get('/oss/policy')
}

// 设置自定义文件名称
function setFileName({
    filePath,
    prefix
}) {
    let filePrefix = prefix //设置新文件路径前缀
    let time = vm.$u.timeFormat(new Date().getTime(), 'yyyy/mm/dd'); //获取时间 年/月/日
    let randomStr = vm.$u.guid(20) //20位的随机字符串
    let fileType = filePath.substring(filePath.lastIndexOf('.')) || 'jpg' //获取图片类型后缀 .jpg .png
    let data = {
        key: `${filePrefix}${time}/${randomStr}${fileType}`,//
        fileName: `${randomStr}${fileType}`,
    }
    return data

//示例:key: testImages/2022/03/10/ulx8M2YF9XP4DPxNjOas.jpg  

//示例:fileName:ulx8M2YF9XP4DPxNjOas.jpg  
}

// 上传文件到oss
export async function uploadOss({
    prefix, //文件前缀缩写
    filePath, //文件的临时路径
    fileType = 'image',
}) {
    let resp = await httpGetOssInfo()
    if (resp.code === 200) {
        let {
            policy,
            accessid,
            signature,
            host,
        } = resp.data
        let fileNamekey = setFileName({filePath, prefix });
        let key = fileNamekey.key
        let fileName = fileNamekey.fileName
        let [err, result] = await uni.uploadFile({
            url: `${host}/`, //阿里云的存储地址
            filePath, //要上传的临时文件路径
            fileType,//文件类型
            name: 'file',//固定的
            formData: {
                key, //文件名
                policy, //后台获取超时时间
                OSSAccessKeyId: accessid, //后台获取临时ID
                success_action_status: '200', //让服务端返回200,不然,默认会返回204
                signature //后台获取签名
            }
        });
        if (err) {
            wx.showToast({
                title: '上传失败,请重试',
                icon: 'none',
                duration: 1000
            })
        } else {
            if (result.statusCode === 200) {
                let data = {
                    key: key,//是上传到阿里云图片的路径
                    fileName: fileName,//文件名称
                    fileType: filePath.substring(filePath.lastIndexOf(
                        '.')+1) || 'jpg' //图片格式
                }
                return data //调用该方法返回的数据
            }
        }
    } else {
        wx.showToast({
            title: '上传失败,请重试',
            icon: 'none',
            duration: 1000
        })
    }
}

使用页面,test.vue

import {uploadOss} from './oss.js'; //oss上传图片引入

methods: {

async submit(){ //上传图片到阿里云

      await uploadOss({
                                prefix: prefix,//自定义文件路径前缀
                                filePath: FilePath //文件路径
                            }).then(res => {
                               console.log(`上传成功+${res.data}`)//这里即为你oss.js return出来的数据
                            }).catch(e => {

                                console.log('上传失败')
                            }); //oss上传

              }
    }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐