unicloud结合上传问题,本文中是以图片为示例,其他文件原理是一样的,后端使用qiniu、multer这款两个npm库,其中要注意的是前端要提前获取token,因为如何放在图片上传之前before-upload方法中会出现拿不到的情况。上传地址根据 七牛云developer.qiniu.com/kodo/1671/r…
前端代码
<template>
<el-upload
class="avatar-uploader"
action="https://up-cn-east-2.qiniup.com"
:show-file-list="false"
:data="dataToken"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
<button @click="beforeUpload">test</button>
</template>
<script setup>
// import axios from "axios";
const dataToken = reactive({
//传到七牛云所需要的token及key
token:"",
key: "",
});
//要提前获取token
// const result = await axios.get("");
// dataToken.token = result.data.data;
const imageUrl = ref("");
//上传前
const beforeUpload = async (file) => {
let fileNameLength = file.name.lastIndexOf("."); // 文件名开始到最后一个点的长度
let fileFormat = file.name.substring(fileNameLength + 1, file.name.length);
fileFormat = fileFormat.toLowerCase();
let imgArr = ["png", "jpg", "jpeg"];
if (!imgArr.includes(fileFormat)) {
ElMessage.error("请选择图片!");
return false;
} else if (file.size / 1024 / 1024 > 5) {
ElMessage.error("请上传小于5MB的图片!");
return false;
}
console.log(file);
dataToken.key = "ordering/" + Date.now() + "." + file.name.split(".")[1];
console.log(dataToken);
};
//上传成功后执行
const handleAvatarSuccess = (res) => {
imageUrl.value = "https://xxxx/" + res.key;
};
</script>
<style scoped>
.cards {
@apply border-0 bg-light-400;
}
</style>
后端云对象代码
npm install qiniu
npm install multer
const qiniu = require("qiniu");
const {
userResdult
} = require('returnMsg')
let body,token;
module.exports = {
_before: function() { // 通用预处理器
const httpInfo = this.getHttpInfo()
body =httpInfo
token = httpInfo.headers.authorization //获取token
},
getQnToken(){
const accessKey = "";//个人中心中有
const secretKey = "";//个人中心中有
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
scope: "",//空间名称
expires: 7200, //过期时间(s) 2h
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
return userResdult('200',"获取七牛云token成功",uploadToken)
}
}